How do I iterate safely under modification with std::unordered_map for embedded targets?

Iterating safely over a modified std::unordered_map in C++ can be challenging, especially in embedded systems where resources are constrained. The goal is to avoid runtime errors due to invalidated iterators when the map is modified during iteration.

One of the common approaches to achieve safe iteration is to use a temporary list of keys to iterate over. This way, even if the unordered map is modified during the iteration, the keys remain unchanged.

Here's an example of how to implement this approach:

#include <unordered_map> #include <vector> #include <iostream> int main() { std::unordered_map myMap = { {1, "One"}, {2, "Two"}, {3, "Three"} }; // Step 1: Create a vector of keys std::vector keys; for (const auto& pair : myMap) { keys.push_back(pair.first); } // Step 2: Iterate over keys and safely modify map for (const int& key : keys) { std::cout << key << ": " << myMap[key] << std::endl; // Modify the map here safely if (key == 2) { myMap.erase(key); // Example modification } } return 0; }

C++ std::unordered_map safe iteration embedded targets iterator invalidation C++ programming data structures