In C++, when working with `std::set`, it's important to handle erasing elements correctly while iterating through the set. Since `std::set` maintains its own order and manages unique keys, you must be cautious about modifying the set during iteration. The proper way to remove elements is to use an iterator and ensure your loop remains valid.
#include <iostream>
#include <set>
int main() {
std::set mySet = {1, 2, 3, 4, 5};
for (auto it = mySet.begin(); it != mySet.end(); ) {
if (*it % 2 == 0) { // If the element is even
it = mySet.erase(it); // Erase returns the next iterator
} else {
++it; // Move to the next element
}
}
// Output the remaining elements
for (int n : mySet) {
std::cout << n << ' ';
}
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?
How do I reserve capacity ahead of time with std::map for embedded targets?