How std::vector grows
Contiguous, dynamic, and occasionally it moves everything you own.
Before you start
A std::vector looks like a Python list or a resizable array: you keep pushing values in and it grows. Behind the scenes it is a plain C-style block of memory that occasionally *moves* to a bigger location.
That move is invisible to your push_back calls but not invisible to any pointer or iterator you were holding into the vector — those go stale the moment the vector relocates.
This lesson watches push_back fill up capacity, allocate a bigger block, copy elements over, and free the old block. Then it shows what happens to an iterator you were holding when that move fires.
Stack
Heap
the elements never live in the vector object itselfsize = how many elements exist. capacity = how many fit before the buffer must be replaced.
Step 1 of 7. An empty vector owns nothing. `std::vector<int> v;` creates a small object on the stack — typically three pointers — with size 0 and capacity 0. No heap allocation has happened yet. The elements will never live inside `v`. `v` only ever holds the address of a buffer, plus how much of it is used.
Step 01 / 07
An empty vector owns nothing
std::vector<int> v; creates a small object on the stack — typically three pointers — with size 0 and capacity 0. No heap allocation has happened yet.
The elements will never live inside v. v only ever holds the address of a buffer, plus how much of it is used.
#include <vector>#include <cstdio>int main() { std::vector<int> v; for (int i = 1; i <= 5; ++i) { v.push_back(i); printf("size %zu cap %zu\n", v.size(), v.capacity()); } int *danger = &v[0]; // valid... v.push_back(6); // ...until this reallocates // *danger is now dangling v.reserve(16); // one allocation, no surprises return 0;}