Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::vector and memory allocation

Tags:

c++

stdvector

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.

like image 858
jbgs Avatar asked Sep 08 '14 19:09

jbgs


People also ask

How much memory does std::vector use?

So there is no surprise regarding std::vector. It uses 4 bytes to store each 4 byte elements. It is very efficient.

Is std::vector stack allocated?

Although std::vector can be used as a dynamic array, it can also be used as a stack.

Does std::vector use dynamic allocation?

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.

How do I allocate a vector in C++?

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.


1 Answers

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.

like image 66
tomer.z Avatar answered Oct 01 '22 08:10

tomer.z