std::vector<T> · C++

reserve / shrink_to_fit

Sets capacity up front so later push_backs do not reallocate.

void reserve(size_type new_cap); void shrink_to_fit();

Complexity

Worst caseO(n) if it reallocates, otherwise O(1)
Extra spaceO(new_cap)

One allocation and one move of the existing elements, instead of several during growth.

Tested example

std::vector<int> v;
v.reserve(1000);              // one allocation up front
const int* first = nullptr;
for (int i = 0; i < 1000; ++i) {
    v.push_back(i);
    if (i == 0) first = v.data();
}
assert(v.data() == first);    // no reallocation happened, so pointers stayed valid
v.shrink_to_fit();            // a non-binding request to release spare capacity
Runs in the test suite on C++23, GCC 15.3 (libstdc++) · examples/cpp/collections/vector_examples.cpp

Parameters

new_cap
Minimum capacity wanted.

Behaviour

Returns
Nothing.
Errors and preconditions
std::length_error if new_cap > max_size(); std::bad_alloc.
Changes
May reallocate; size() is unchanged.
Memory and invalidation
If it reallocates, all iterators, pointers and references are invalidated. After reserve(n), push_backs up to size n keep them valid.