stl · high
Vector Growth & Reallocation
Watch push_back fill free slots cheaply, then reallocate to double capacity and move elements when full.
🔑 Key line
push_back is amortized O(1): when size == capacity the vector reallocates to ~2x and moves elements (invalidating iterators).
The code
std::vector<char> v; // size & capacity grow on demand// v already holds A, B with capacity 4v.push_back('C'); // free slot -> O(1)v.push_back('D'); // fills capacity (4/4)v.push_back('E'); // full -> reallocate (2x), move, add// a reallocation invalidates iterators, pointers & referencesWhat this lesson walks through
- 01size vs capacity
- 02push_back('C') - free slot, O(1)
- 03push_back('D') - now full
- 04push_back('E') - full, allocate 2x
- 05move elements to the new buffer
- 06construct E; old buffer freed
- 07Why push_back is amortized O(1)
- 08reserve() avoids reallocations
A vector tracks two numbers: size (elements in use) and capacity (slots allocated). Here it holds A and B but has room for 4.
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of Vector Growth & Reallocation and 100+ animated C++ interview lessons.