stl · high
Iterator Invalidation
Why an iterator into a vector dangles after a reallocation, and how reserve / indices / erase's return value avoid it.
🔑 Key line
Reallocation (push_back/insert/resize past capacity) invalidates vector iterators, pointers & refs; erase invalidates from that point on.
The code
std::vector<int> v = {10, 20, 30, 40};auto it = v.begin() + 1; // points at 20v.push_back(50); // may REALLOCATE -> it dangles!// *it; // undefined behavior if reallocated
v.reserve(8); // fix A: pre-allocate, no reallocsize_t i = 1; // fix B: an index survives reallocit = v.erase(it); // erase returns the next valid iteratorWhat this lesson walks through
- 01An iterator points INTO the buffer
- 02push_back full -> reallocation moves the buffer
- 03it now dangles -> UB
- 04Fix A: reserve() up front
- 05Fix B: use an index, not an iterator
- 06erase invalidates from that point on
- 07The invalidation rules
it = v.begin() + 1 holds a raw address inside the vector's buffer - it points directly at the element 20.
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of Iterator Invalidation and 100+ animated C++ interview lessons.