What is iterator invalidation in C++?
A change to a container can make old iterators, pointers and references invalid. Using them is undefined behavior. For a vector, push_back can move all the items to a bigger memory block when the capacity is full.
#include <iostream>
#include <vector>
int main() {
std::vector<int> v = {1, 2, 3};
const int* before = v.data();
v.reserve(1000); // the data moves to a new place
const int* after = v.data();
std::cout << "data moved: " << (before != after) << '\n';
// an iterator or pointer taken before reserve() must not be used now
}
Output
data moved: 1
| Container | After insert | After erase |
|---|---|---|
| vector | All invalid if it reallocates, else from the insert point | From the erased item onward |
| list, map, set | Stay valid | Only the erased item is invalid |
| unordered_map | Can all become invalid on a rehash | Only the erased item |
Safe habits: use indexes, call reserve early, and do not keep iterators across changes. See Vectors.
Learn more about the similar topics:
| Tutorials |
|---|
| C++ Templates and Generic Programming |
| C++ STL Containers: map, set, unordered_map, queue and stack |
| C++ Algorithms and Iterators |
| Exercises & Assignments |
|---|
| Write a generic maximum template |
| Count the frequency of words with a map |
| Remove duplicates from a vector and keep the order |