std::vector and how it grows
Size versus capacity, the doubling strategy, and why push_back is fast on average but occasionally slow.
- Distinguish a vector's size from its capacity
- Explain amortised O(1) push_back and the cost of a reallocation
- Use reserve to avoid reallocations, and know what they invalidate
std::vector is the default container in C++: a contiguous array on the heap that grows on demand.
std::vector<int> my_vector = {1, 2, 3, 4, 5};
my_vector.push_back(6); // 1 2 3 4 5 6
my_vector.pop_back(); // 1 2 3 4 5
It tracks two numbers. Size is how many elements it holds; capacity is how many fit in the block it has already allocated. While size is below capacity, push_back just writes into the next free slot. When they are equal, the vector must allocate a bigger block, move every element across and free the old one.
Doubling
How much bigger? Printing the capacity after each push_back with g++ 13’s libstdc++ gives 1, 2, 4, 4, 8, 8, 8, 8, 16, … — it doubles. That choice is what makes push_back cheap on average: after 40 insertions only 63 elements have been moved in total, fewer than two per element, however large the vector gets. This is amortised constant time: most calls are trivial and the occasional expensive one is paid for by all the cheap ones before it.
reserve
When the final size is known, reserve allocates once. The second half of 11vector.cpp does exactly that:
std::vector<int> my_vector1;
my_vector1.reserve(10);
for (int i = 0; i < 10; i++) {
std::cout << "size: " << my_vector1.size() << '\n';
std::cout << "Capacity: " << my_vector1.capacity() << '\n';
my_vector1.push_back(i);
}
The output shows size climbing 0 to 9 while capacity stays at 10 throughout: no reallocation ever happens.
What a reallocation breaks
Moving to a new block changes every element’s address. Any pointer, reference or iterator into the old block now points at freed memory:
std::vector<int> v = {1, 2, 3, 4}; // capacity 4
int &first = v[0];
v.push_back(5); // reallocates
std::cout << first; // undefined behaviour
This is one of the most common C++ bugs, and it is invisible in testing whenever capacity happens to be large enough. The snake game’s Snake.hpp mentions this very reason for using std::list (whose nodes never move) for the snake’s body.
One small detail in 11vector.cpp: print(std::vector<int> vector) takes its argument by value, so every call copies the whole vector. Lesson 5 fixes that with const std::vector<int>&.
Try it yourself. Push 1,000 integers into an empty vector and print the capacity every time it changes. How many reallocations happen? Predict the number from the doubling rule first (\(\lceil \log_2 1000 \rceil + 1\)), then check. Finally, print v.data() alongside to watch the block move.