How do I avoid iterator invalidation with std::unordered_map?

When working with std::unordered_map in C++, avoiding iterator invalidation is crucial for ensuring the integrity of your data structures during modifications. In C++, iterators can become invalidated when the container is modified, such as through insertions or deletions. Here's an approach to safely manage iterators while interacting with an std::unordered_map.

One effective way to avoid iterator invalidation is to store iterators that you intend to use for later access before performing any modifications to the unordered_map.


#include <iostream>
#include <unordered_map>

int main() {
    std::unordered_map myMap = {
        {1, "One"},
        {2, "Two"},
        {3, "Three"}
    };

    // Store iterators before modification
    for (auto it = myMap.begin(); it != myMap.end();) {
        if (it->first % 2 == 0) { // Condition to erase some elements
            it = myMap.erase(it); // Erase returns the next iterator
        } else {
            ++it; // Increment only if not erased
        }
    }

    // Print remaining elements
    for (const auto& pair : myMap) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }

    return 0;
}
    

C++ std::unordered_map iterator invalidation C++ containers iterator safety C++ programming