Suppose reserve(N)
is called multiple times one after another immediately. Will the earlier reserve(N1)
get added up or overwritten ?
Unlike std::string
it is not possible to call reserve()
for std::vector
to shrink the capacity()
.Calling reserve()
with an argument that is less than the current capacity()
is a no-op. Hence the last reserve()
call which increases the current capacity will hold good.
If the earlier reserve(N1)
gets overwritten with the latest call, then what happens if the latest reserve(Nn)
demands less number of slots ?
Calling reserve()
with an argument that is less than the current capacity()
is a no-op.
After declaring vector if we have simply push_back() X elements, and then we call reserve(N). Will the already push_back() X elements counted in N ?
reserve()
just allocates(reserves) enough number of elements so Yes. Note that after calling reserve()
only the capacity()
of the vector is changed the size()
remains unaffected.If you would need to create as many elements and not just reserve memory you should be using resize()
.
Suppose, if the vector has some X
pushed elements and now if we push_back()
1 more element (X+1)
, then that object would have to get relocated; but we haven't yet performed push_back()
. What happens if we call reserve()
now ? Will the object get relocated immediately ? If not, then how is the space reserved ?
Yes, the relocation will happen but it depends. As said before, reserve()
allocates enough memory to store as many elements as the argument passed to it. So if this number of elements is greater than what can be accommodated in current vector capacity()
, relocation will happen.
Standard References:
C++03 23.2.4.2 vector capacity [lib.vector.capacity]
void reserve(size_type n);
Effects: A directive that informs a vector of a planned change in size, so that it can manage the storage allocation accordingly. After reserve()
, capacity()
is greater or equal to the argument of reserve if reallocation happens; and equal to the previous value of capacity()
otherwise. Reallocation happens at this point if and only if the current capacity is less than the argument of reserve()
.
Complexity: It does not change the size of the sequence and takes at most linear time in the size of the sequence.
Throws: length_error if n > max_size()
.248)
Notes: Reallocation invalidates all the references, pointers, and iterators referring to the elements in the sequence. It is guaranteed that no reallocation takes place during insertions that happen after a call to reserve()
until the time when an insertion would make the size of the vector greater than the size specified in the most recent call to reserve()
.