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

In C++, when working with `std::unordered_set`, iterator invalidation can occur when the underlying data structure is modified. To avoid this issue, it is essential to understand how iterators work and when they become invalidated.

Here is an example that demonstrates how to safely modify an `std::unordered_set` without invalidating iterators:

#include #include int main() { std::unordered_set mySet = {1, 2, 3, 4, 5}; std::unordered_set::iterator it; // Create a vector to hold elements to remove std::vector toRemove; // First, gather elements to remove for (it = mySet.begin(); it != mySet.end(); ++it) { if (*it % 2 == 0) { // Remove even numbers toRemove.push_back(*it); } } // Now, remove elements safely for (int num : toRemove) { mySet.erase(num); } // Iterators are still valid for (it = mySet.begin(); it != mySet.end(); ++it) { std::cout << *it << " "; } std::cout << std::endl; return 0; }

C++ std::unordered_set iterator invalidation data structure modifications C++ best practices