How do I erase elements while iterating with std::set for large datasets?

When dealing with large datasets in C++, using `std::set` can be challenging, especially when you want to erase elements while iterating through the set. It's crucial to ensure that the iterator remains valid after an erase operation. Below is an example illustrating the correct way to erase elements from a `std::set` while iterating over it.

#include #include int main() { std::set mySet = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; for (auto it = mySet.begin(); it != mySet.end(); ) { if (*it % 2 == 0) { // Check if the element is even it = mySet.erase(it); // Erase returns the next iterator } else { ++it; // Move to the next element } } // Print remaining elements std::cout << "Remaining elements: "; for (const auto& element : mySet) { std::cout << element << " "; } std::cout << std::endl; return 0; }

C++ std::set iterator erase elements large datasets