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

Iterator invalidation is a common concern when using containers from the C++ Standard Library, including `std::multiset`. This container allows multiple elements with equivalent keys but can invalidate iterators under certain conditions. To avoid iterator invalidation with `std::multiset`, consider the following best practices:

  • Use Stable Iterators: Always ensure that your iterations do not attempt to modify the multiset while iterating through it.
  • Store Iterators: Instead of directly modifying elements, store iterators to the elements you need to work with, and modify the multiset after you finish iterating.
  • Use Functions to Modify: Consider using functions to encapsulate modifications to the multiset that operate on a snapshot of the iterators.

Here is an example of how to safely work with `std::multiset` without invalidating iterators:

#include <set> #include <iostream> int main() { std::multiset ms = {1, 2, 2, 3, 4, 5}; // Store iterators before modifying the multiset std::multiset::iterator it = ms.find(2); // Safely removing elements after storing iterators while (it != ms.end()) { // This is safe because it doesn't invalidate the previous iterator it = ms.erase(it); // Erase returns the next iterator } // Output the contents of the multiset for (const auto& value : ms) { std::cout << value << " "; } return 0; }

C++ std::multiset iterator invalidation C++ Standard Library multiset examples C++ iterators