How do I avoid iterator invalidation with std::map?

When working with std::map in C++, iterator invalidation can be a significant issue, especially when modifying the map while iterating through it. To avoid iterator invalidation, consider the following strategies:

  • Use std::map::erase() carefully: When you erase an element, it invalidates only the iterator pointing to that element, so ensure you store the next iterator before erasing.
  • Copy the entries to a separate container: If you need to modify elements while iterating, consider copying the required entries into another container, then process them.
  • Use std::map::find() to get iterators safely: Instead of erasing while iterating, you can use temporary iterators to mark elements for removal after the loop.

Here’s an example of safely erasing elements while iterating through a std::map:

#include <iostream> #include <map> int main() { std::map myMap = { {1, "apple"}, {2, "banana"}, {3, "cherry"} }; for (auto it = myMap.begin(); it != myMap.end(); ) { if (it->first % 2 == 0) { it = myMap.erase(it); // Safe to erase and get next iterator } else { ++it; // Move to the next element } } for (const auto& pair : myMap) { std::cout << pair.first << ": " << pair.second << std::endl; } return 0; }

C++ std::map iterator invalidation C++ map examples safe iteration