I guess most people understand that the complexity of size() function is not guaranteed to be constant. Though in some implementations, it is constant.
The G++ compiler is probably the most commonly used compiler. So, in G++’s implementation, what’s the complexity of size()? If it varies by different containers, what containers have linear complexity? For the most commonly used ones (such as list, vector, deque, set, & map), are they all constant?
It may change depending on the version of the standard library.
For GCC recent versions (atleast up to 4.6.2)
Listand ones based off ofListare not constant time, but implemented as{ return std::distance(begin(), end()); }.MSVC standard library keeps track of size as it changes and just returns its value (which makes
splice()O(n) because it has to count when it splices).From my
/usr/include/c++/4.6.2/bits/stl_list.h:vector,set,deque, andmapare constant time. ,this is
std::deque‘squeueandstackare actually container adapters and depend on the underlying container, which can be specified. However the default isdeque, which is constant.