Zack Lee
Zack Lee

Reputation: 3074

Correct way to reserve non-empty std::vector before push_back()

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

Answers (3)

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

Holt
Holt

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 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(). If an exception is thrown other than by the move constructor of a non-Cpp17CopyInsertable type, there are no effects.

Upvotes: 3

Bob Fang
Bob Fang

Reputation: 7411

Increase the capacity of the vector to a value that's greater or equal to new_cap. If new_cap is greater than the current capacity(), new storage is allocated, otherwise the method does nothing.

From the documentation here it is clear that it is the total size.

Upvotes: 5

Related Questions