Use resize() to set the element count
resize(n) makes the vector hold exactly n elements:
#include <iostream>
#include <vector>
int main() {
std::vector<int> v{1, 2, 3};
v.resize(5); // 1 2 3 0 0
v.resize(6, 9); // 1 2 3 0 0 9
v.resize(2); // 1 2
std::cout << v.size() << '\n'; // 2
}
Three things to know:
- When the vector grows, the new elements get a starting value. For
int, that value is 0. Forstd::string, the new elements are empty strings. - Pass a second argument, as in
v.resize(6, 9), to choose the value of the new elements. - When the vector shrinks, the extra elements are removed. The capacity does not change.
Use reserve() to plan for growth
reserve(n) sets the capacity to at least n. It does not change the size, so no elements are added:
std::vector<int> v;
v.reserve(100);
std::cout << v.size() << '\n'; // 0
Reserving makes sense when you know roughly how many values you will add. The vector can then grow with fewer memory reallocations while you call push_back.
Use clear() and shrink_to_fit()
clear() removes every element, so the size becomes 0. The capacity stays the same.
shrink_to_fit() asks the vector to release its unused capacity. It is only a request, so the implementation may ignore it:
v.clear(); // size() is 0, capacity unchanged
v.shrink_to_fit(); // request to release unused memory
When capacity changes
Growing past the current capacity makes the vector allocate new memory and move its elements. After that, pointers, references and iterators that pointed at the old elements can no longer be used safely. Keep this in mind if you hold a pointer into a vector while you resize it or add elements. For the memory side of this, see c heap vs stack.
push_back versus resize
push_back() and emplace_back() add one element at the end and grow the vector as needed, so you usually do not need resize() for that. Use resize() when you want a specific element count in one step.
Start with the right size
If you know the size when you create the vector, a count in the constructor is often simpler than calling resize() afterward. Those forms are covered in c vector initialization.
Summary
Use resize() to set the element count, reserve() to set capacity without adding elements, and clear() to remove everything. How the count and capacity differ is covered in How does size() work in C++?