It seems that every time you append a new element to a std::vector
, if there aren't empty elements, the number of allocated elements is doubled (at least in GCC 4.9). I think this is done in order to achieve amortized constant time complexity.
E.g., 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.
In memory constrained systems, is there any way to prevent this behaviour even if it is at the cost of a performance penalty?
Moreover, would it be possible to indicate that it should allocate only a fixed number of elements instead of doubling it?
I know I can call std::vector::reserve()
before adding new elements, but it seems a mess in my case... calling std::vector::shrink_to_fit()
is another approach, but also inconvenient.
So there is no surprise regarding std::vector. It uses 4 bytes to store each 4 byte elements. It is very efficient.
Although std::vector can be used as a dynamic array, it can also be used as a stack.
Note that in both the uninitialized and initialized case, you do not need to include the array length at compile time. This is because std::vector will dynamically allocate memory for its contents as requested.
You can use the reserve() and resize() methods to have it allocate enough memory to fit a given amount of items: std::vector<int> vec1; vec1. reserve(30); // Allocate space for 30 items, but vec1 is still empty.
No there is no way.
Your only option is to write your own vector data structure and that way you can do whatever you want with it (or you could just copy an implementation of the internet/c++ library and change what you need and include that new vector in your program).
Actually you can also use an array and the realloc
command.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With