Std :: vector and memory allocation

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.

+7
c ++ stdvector
source share
1 answer

There is no way.

Your only option is to write your own vector data structure, and in this way you can do whatever you want with it (or you can just copy the internet / C ++ library implementation and change what you need and include this new vector in your program).

In fact, you can also use the array and the realloc command.

+5
source share

All Articles