How do I erase elements while iterating with std::unordered_map for embedded targets?

When iterating over an `std::unordered_map` in C++, you may encounter scenarios where you need to erase elements while still accessing the map. Directly modifying the container during iteration can lead to invalid iterators and undefined behavior. To handle this safely, you can make use of the iterator returned by the `erase` method of the unordered_map. This allows you to continue iterating through the remaining elements even after deleting some.

C++, erase elements, std::unordered_map, iteration, embedded targets, safe iteration
This article provides insight on how to safely erase elements from an std::unordered_map while iterating, especially in scenarios relevant to embedded systems.

#include <iostream>
#include <unordered_map>

int main() {
    std::unordered_map myMap = {
        {1, "Apple"},
        {2, "Banana"},
        {3, "Cherry"},
        {4, "Date"}
    };

    for (auto it = myMap.begin(); it != myMap.end(); ) {
        if (it->second == "Banana") {
            it = myMap.erase(it); // Erase and get next iterator
        } else {
            ++it; // Just move to the next element
        }
    }

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

    return 0;
}
    

C++ erase elements std::unordered_map iteration embedded targets safe iteration