Reputation: 3074
I'm confused whether N
in vector::reserve(N)
is the number of elements that it expects to be added on top of the current vector size or the total space of the vector.
For example,
#include <iostream>
#include <vector>
int main()
{
std::vector<int> foo;
foo.reserve(3);
foo.push_back(1);
foo.push_back(2);
foo.push_back(3);
foo.reserve(foo.size() + 2);// Should this be foo.reserve(2)?
foo.push_back(4);
foo.push_back(5);
}
Should the foo.reserve(foo.size() + 2)
be just foo.reserve(2)
?
Upvotes: 2
Views: 904
Reputation: 29017
The argument needs to be foo.size() + 2
. To quote cppreference
[
reserve
will] increase the capacity of the vector to a value that's greater or equal to new_cap.
Upvotes: 2
Reputation: 37661
You should call foo.reserve(foo.size() + 2)
, see [vector.capacity] (emphasis is mine):
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 ofreserve
if reallocation happens; and equal to the previous value ofcapacity()
otherwise. Reallocation happens at this point if and only if the current capacity is less than the argument ofreserve()
. If an exception is thrown other than by the move constructor of a non-Cpp17CopyInsertable type, there are no effects.
Upvotes: 3