It seems that every time you add a new element to std::vector , if there are no empty elements, the number of selected elements doubles (at least in GCC 4.9). I think this is done in order to achieve an average constant time complexity.
For example, after running this code:
v.push_back (1); v.push_back (2); v.push_back (3); v.push_back (4); v.push_back (5); v.shrink_to_fit(); // capacity is 5 now v.push_back (6); std::cout << v.capacity () << std::endl;
The output is 10.
On systems with limited memory, is there a way to prevent this behavior, even if it is associated with performance degradation?
Furthermore, is it possible to indicate that it should select only a fixed number of elements, and not double it?
I know I can call std::vector::reserve() before adding new elements, but in my case it seems messy ... calling std::vector::shrink_to_fit() is a different approach, but also inconvenient.
c ++ stdvector
jbgs
source share