The following code produces the following output and ends up in kind of an endless loop with 100% cpu load.
#include <iostream>
#include <set>
class Foo{};
void delete_object_from_set(std::set<Foo *>& my_set, Foo* ob)
{
std::set< Foo *>::iterator setIt;
std::cout << "Try to delete object '" << ob << "'..." << std::endl;
for(setIt = my_set.begin(); setIt != my_set.end(); ++setIt)
{
Foo * tmp_ob = *setIt;
std::cout << "Check object '" << tmp_ob << "'..." << std::endl;
// compare the objects
//
if(ob == tmp_ob)
{
// if the objects are equal, delete this object from the set
//
std::cout << "Delete object '" << tmp_ob << " from set..." << std::endl;
setIt = my_set.erase(setIt);
std::cout << "Deleted object '" << tmp_ob << " from set..." << std::endl;
}
}
std::cout << "loop finished." << std::endl;
};
int main()
{
Foo* ob = new Foo();
std::set< Foo * > my_set;
my_set.insert(ob);
delete_object_from_set(my_set, ob);
std::cout << "finished" << std::endl;
return 0;
}
The output:
Try to delete object '0x563811ffce70'...
Check object '0x563811ffce70'...
Delete object '0x563811ffce70 from set...
Deleted object '0x563811ffce70 from set...
so it does not finish, having 100% cpu load.
I know how to do it correctly (see below), but I cannot understand what is going on here. It's not an endless loop, since then it should output something continuously, but it just keeps doing something. Any idea what?
How to do it the right way: Deleting elements from std::set while iterating and How to remove elements from an std::set while iterating over it