Search code examples
c++vectorstdstdvectorallocation

std::vector preallocation (size n, capacity n + 2)


My use-case is the following: A vector of size n read from a binary file.

Among other variants (iostreams, in my case custom code doing decompression), I can do something with semantics like this:

vector<myElem> v;
v.resize(n); // from my understanding v now has size n and capacity n
fread(v.data(), sizeof(myElem), n, myFile);

However, later I will have to (repeatedly) add and remove two elements to such a vector. (While this sounds pretty stupid, it can have positive effects to add sentinel values to lists so that intersections of sorted lists do not have to add comparisons for bound-checking).

For that, I would love to prealloacte a vector with size n and capacity n + 2. I think I could do something like:

vector<myElem> v;
v.resize(n + 2); // from my understanding v now has size n + 2 and capacity n + 2 
v.pop_back();
v.pop_back(); // v now has size n and most probably still has capacity 2 (unless n is pretty small)
fread(v.data(), sizeof(myElem), n, myFile);

Obviously, this is neither pretty nor guaranteed to behave as I would liek it to. In practice, I think it really should behave that way for big n and if small n should ever occur, a reallocation doesn't matter.

Still, it would be great to hear if there are better ways.

edit:

I am unsure how I can make use of reserve in my case. If I reserve a capacity of n + 2, the vector still has size 0. If I resize to n, i also change the capacity.

If I resize first and then reserv, I allocate memory two times and copy the whole vector in the process.


Solution

  • You can use v.reserve(n + 2) to change the vector's capacity without altering its size. Take a look at the documentation to better understand what is going on.