I've read this SO post, and this one too regarding
the erasure of elements from a std::set
during iteration.
However, it seems that a simpler solution exists in C++17:
#include <set>
#include <iostream>
int main(int argc,char **argv)
{
std::set<int> s;
s.insert(4);
s.insert(300);
s.insert(25);
s.insert(-8);
for (auto it:s)
{
if (it == -8)
{
s.erase(it);
}
}
std::cout << "s = {";
for (auto it:s)
{
std::cout << it << " ";
}
std::cout << "}\n";
return 0;
}
When I compile and run it everything goes perfect:
$ g++ -o main main.cpp
$ ./main
s = {4 25 300 }
Are there any caveats in erasing elements like that? thanks.