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

When working with std::multimap in C++, iterator invalidation can be a concern, especially when inserting or deleting elements. In general, you want to avoid performing operations that can lead to invalidated iterators. This can be particularly tricky with a std::multimap because duplicate keys allow multiple entries and modifications that might affect iterators. Here are some strategies to avoid iterator invalidation:

  • Use iterators carefully: Avoid storing iterators to elements that you may modify.
  • Prefer to use `find` or `equal_range` for access: This will help to get valid iterators even after modifications.
  • Refrain from erasing elements while iterating through the multimap directly, as this can invalidate iterators. Consider using a copy of the keys to erase after the iteration.

Here's a simple example demonstrating the safe use of iterators with std::multimap:

#include <iostream> #include <map> int main() { std::multimap myMap; myMap.insert({1, "One"}); myMap.insert({2, "Two"}); myMap.insert({2, "Deux"}); myMap.insert({3, "Three"}); // Using iterator for safe traversal for (auto it = myMap.begin(); it != myMap.end(); /* no increment here */) { // Example of safe access std::cout << it->first << ": " << it->second << std::endl; // Example of conditional erase (without invalidating iterator) if (it->first == 2) { it = myMap.erase(it); // erase returns next valid iterator } else { ++it; // move to next only if not erasing } } return 0; }

C++ std::multimap iterator invalidation C++ iterators multimap usage