How do I erase elements while iterating with std::unordered_map for large datasets?

When working with large datasets in C++ and using `std::unordered_map`, it's essential to handle element removal correctly while iterating. Directly modifying the container while iterating can invalidate iterators and lead to undefined behavior. Here’s how you can safely erase elements in an `std::unordered_map`.

C++, std::unordered_map, erase elements, iterator, large datasets, performance optimization
Learn how to safely erase elements from std::unordered_map while iterating through it in C++. This guide provides best practices for handling large datasets efficiently.

#include <iostream>
#include <unordered_map>

int main() {
    std::unordered_map<int, std::string> myMap = {
        {1, "one"},
        {2, "two"},
        {3, "three"},
        {4, "four"},
        {5, "five"}
    };

    for (auto it = myMap.begin(); it != myMap.end(); ) {
        if (it->first % 2 == 0) { // Remove even keys
            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 erase elements iterator large datasets performance optimization