CKTIS / C++
std::vector::reserve — reserving capacity without changing size
`reserve(n)` makes room for at least `n` elements in total without creating any elements. Use it before a batch of appends when you know the final count or a reasonable upper bound.
Version: ISO C++23; implementation support may vary
Syntax
constexpr void reserve(size_type new_cap);std::vector::reserve is a member function declared in <vector>. In C++23 its declaration is constexpr void reserve(size_type new_cap);. The argument is a total element count, not an extra count or a byte count. After a successful call, capacity() >= new_cap and size() is unchanged. Unlike resize(), reserve() neither adds nor removes elements. v[i] is valid only for i < v.size(), even if the capacity is larger.
If new_cap <= capacity(), the call does nothing. Otherwise it reallocates, invalidating all existing pointers, references, and iterators to elements, as well as the old end(). Without reallocation, reserve() itself invalidates none of them. After a successful call, insertions do not reallocate until one would exceed the current capacity. Even an append without reallocation still invalidates the old end().
Reallocation takes at most linear time in size(). T must be Cpp17MoveInsertable into the vector. A request above max_size() throws std::length_error; the allocator can also throw, typically std::bad_alloc. If an exception is thrown, the operation has no effect, except when it comes from the move constructor of a type that is not Cpp17CopyInsertable into the vector. In that case the effects are unspecified.
Reserve once when you know the final count or a reasonable upper bound, for example when collecting matching indices or building a sorted report. Avoid calling reserve(size() + 1) before every append: it can increase reallocations. Add elements with push_back() or emplace_back(); writing through std::back_inserter(v) calls push_back(). std::pmr::vector follows the same size, capacity, and invalidation rules.
Examples
#include <array>
#include <cstddef>
#include <iostream>
#include <vector>
int main() {
const std::array<int, 4> scores{-3, 8, 0, 5};
std::vector<std::size_t> selected;
selected.reserve(scores.size());
std::cout << "size=" << selected.size() << '\n'
<< "capacity>=4=" << std::boolalpha
<< (selected.capacity() >= scores.size()) << '\n';
for (std::size_t i = 0; i < scores.size(); ++i) {
if (scores[i] > 0) {
selected.push_back(i);
}
}
std::cout << "selected:";
for (const auto index : selected) {
std::cout << ' ' << index;
}
std::cout << "\nsize=" << selected.size() << '\n';
}Result
size=0 capacity>=4=true selected: 1 3 size=2
`scores.size()` bounds the number of matches. The vector is still empty after reservation, and `push_back()` adds only the indices `1` and `3`, not the scores. The program checks the capacity lower bound instead of printing an exact capacity.
Related lessons
- C++ · Lesson 5 · Advanced · Version: 3
- C++ · Lesson 11 · Advanced · Version: 3
- C++ · Lesson 18 · Advanced · Version: 3
- C++ · Lesson 21 · Advanced · Version: 3
- C++ · Lesson 29 · Advanced · Version: 3
- C++ · Lesson 30 · Advanced · Version: 3
- C++ · Lesson 32 · Advanced · Version: 3
- C++ · Lesson 34 · Advanced · Version: 3
- C++ · Lesson 57 · Advanced · Version: 3