How do I iterate safely under modification with std::unordered_map for large datasets?

Iterating safely through a std::unordered_map while modifying it can be particularly challenging, especially for large datasets. One common approach is to use iterators to access the elements while safely making modifications. Below is an example demonstrating a safe iteration method using a temporary copy of the keys.

When modifying an unordered_map during iteration, always ensure to create a separate collection of elements to iterate over to avoid invalidating the iterator. This prevents runtime errors or unexpected behavior.


// Example of safe iteration and modification
#include <iostream>
#include <unordered_map>
#include <vector>

int main() {
    std::unordered_map myMap = {{1, 10}, {2, 20}, {3, 30}};
    std::vector keys;

    // Copy keys to a separate vector
    for (const auto& pair : myMap) {
        keys.push_back(pair.first);
    }

    // Iterate over the keys and modify the map safely
    for (int key : keys) {
        if (myMap[key] > 15) {
            myMap[key] += 10; // Safely modify the map
        }
    }

    // Output the modified map
    for (const auto& pair : myMap) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }

    return 0;
}
    

C++ std::unordered_map iteration modify safely large datasets