Table of Contents

C++ Iterator invalidation

Iterator invalidation occurs when a container operation (like insert, erase, push_back, or resize) makes existing iterators or references unsafe to use. Different containers have different invalidation rules: vector invalidates on reallocation; list invalidates only the erased element; map invalidates only the erased element.

Check container-specific iterator invalidation rules before modifying containers; prefer container algorithms like std::erase (C++20) or the erase-remove idiom.

Example

This example shows how vector reallocation invalidates iterators and demonstrates safety.

// compile: g++ -std=c++20 -o invalid invalid.cpp
// run: ./invalid
// description: iterator invalidation and how to safely modify containers
 
#include <iostream>
#include <vector>
#include <algorithm>
 
int main() {
    std::vector<int> v{1, 2, 3, 4, 5};
 
    // Unsafe: push_back may reallocate, invalidating iterator
    // auto it = v.begin();
    // v.push_back(6);
    // it->print();  // undefined behavior
 
    // Safe: erase returns new iterator
    auto it = v.begin() + 2;
    it = v.erase(it);  // erase element at [2], it now points to next
 
    // Safe: algorithms handle invalidation
    v.erase(std::remove(v.begin(), v.end(), 3), v.end());
 
    for (int x : v) std::cout << x << " ";
    std::cout << "\n";
 
    return 0;
}