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

When working with `std::map` in C++, you may find yourself needing to erase elements while iterating through the map. This is a common requirement, especially in embedded systems where memory management is crucial. However, iterating directly with an iterator while modifying the map can lead to undefined behavior. To safely erase elements, it's essential to use the iterator returned by the `erase` method or to store the next iterator before erasing the current element.

The following example demonstrates how to safely erase elements from a `std::map`:

#include #include int main() { std::map myMap; // Inserting elements into the map myMap[1] = "One"; myMap[2] = "Two"; myMap[3] = "Three"; // Iterating and erasing elements for (auto it = myMap.begin(); it != myMap.end(); ) { if (it->first % 2 == 0) { // Let's say we want to erase even keys it = myMap.erase(it); // Erase returns the next iterator } else { ++it; // Increment only if no erase occurred } } // Output remaining elements for (const auto& pair : myMap) { std::cout << pair.first << ": " << pair.second << std::endl; } return 0; }

C++ std::map erase iterating embedded systems memory management C++ example