I have a for loop with a map like this.
std::map<int,std::string> mymap = {{1,"a"},{2,"b"},{3,"c"}};
for(std::map<int,std::string>::iterator it = mymap.begin(); it!=mymap.end(); ++it)
{
if(it->first==3)
{
mymap.erase(it);
}
}
std::cout << mymap.rbegin()->second << std::endl;
The output is "b" as expected. The question is: Can this lead to an infinite loop (or a crash) somehow? I mean after
erase(it)
the iterator it is invalid. If the erased item was not the last one, it should be ok, because "it" is incremented after the erasion and when the condition is evaluated it points to mymap.end() at max. But if I erase the last one, after erasion mymap.end() should be after the last remaining item, and then it is incremented anyways. Can't it somehow run out of range? Shouldn't I use something like
for(std::map<int,std::string>::iterator it = mymap.begin(); it!=mymap.end(); ++it)
{
std::map<int,std::string>::const_iterator tempit = it;
const bool lastItemErased = ++tempit == mymap.end();
if(it->first==3)
{
mymap.erase(it);
}
if(lastItemErased) break;
}
to be safe?
note: both of the above runs and behaves as expected if I try to erase the element with key 3 and 2. I don't see how is this possible and why doesn't it crash. How can I increment an invalid iterator?
update: It has to work with c++03. I initialized the map like this, to post the question more easily.