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

ContainerAfter insertAfter erase
vectorAll invalid if it reallocates, else from the insert pointFrom the erased item onward
list, map, setStay validOnly the erased item is invalid
unordered_mapCan all become invalid on a rehashOnly 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
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.