In C++, std::vector::reserve(n) asks the vector to make sure its capacity() is at least n. The number of elements (size()) does not change.
Call it before a loop of push_back() when you already know the final count. That avoids several reallocations and keeps old pointers valid longer. Include <vector> to use it.
This is a member of std::vector<T>, a dynamic contiguous array. Elements sit in one block, so v[i] and data() are fast. Growing past capacity() reallocates and can invalidate iterators, references, and pointers. Prefer push_back / pop_back at the end; middle inserts shift elements.
Syntax
Pass the number of elements you expect to store.
C++
v.reserve(1000);
for (int i = 0; i < 1000; ++i) {
v.push_back(i);
}
Call
What it does
v.reserve(1000)
Ensures capacity is at least 1000. Size is unchanged. If capacity was already larger, nothing happens.
reserve() does not create elements. Use resize(n) when you want n real elements (default-constructed or filled).
Library declarations
C++
void reserve(size_type new_cap);
Parameters
Parameter
Description
new_cap
Required. The minimum capacity you want. If it is greater than max_size(), the call throws std::length_error.
Return Value
Return Value
Description
Nothing
reserve() returns void. Check capacity() afterwards if you want to see the new room.
C++ Examples
Example 1 — Basic reserve()
Reserve room, then push a few values and print size and capacity.