The pitfalls of size in stl

高洛峰
Release: 2016-11-22 15:12:39
Original
1470 people have browsed it

When I first joined the company last year, there was LRUCache in the company's basic library, and the implementation inside used std::list. But the function that calculates std::list directly uses the size() method in stl. As a result, during the stress test, the performance was stuck here.
Today, a colleague found another queue implementation in the basic library, which also used std::list. The size() method was also used when getting the number of elements.
Unfortunately, the company's basic library only exposes the header files, and it is impossible to check one by one whether this pit will exist in other places.

Let’s take a look at the implementation of the size() method in stl:

size_type    
  size() const
      { return std::distance(begin(), end()); }
Copy after login

The g++ version of the above code is 4.2.1

Obviously, the complexity is O(N). When there are many elements in the list, the calculation will be very slow. Therefore, when using std::list, you must remember to maintain a count yourself.


Related labels:
stl
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template