Consider the following code
std::set<int> int_set = {1, 2, 3, 4};
for(const auto& key : int_set)
{
if(key == 2)
{
int_set.erase(key);
break;
}
}
The code runs as expected, but is it safe?
It feels wrong to be using a reference to a key to erase itself from a set, as presumably once the erase has happened the reference is no longer valid.
Another code snippet with the same potential problem would be
std::set<int> int_set = {1, 2, 3, 4};
const auto& key = *int_set.find(2);
int_set.erase(k);