Skip to main content
gamedev.net
🔒 Locked

std::map and erase

Started by Paradigm Shifter 2 replies 750+ views
Original Post
Paradigm Shifter
Paradigm Shifter
Is it safe to ++ a map iterator when its equal to the end()? Or -- when its equal to begin()? map::erase returns an iterator to the next valid element, or end() if the last element was erased, so if we have this code
for( itMap = myMap.begin() ; itMap != myMap.end() ; ++itMap )
{
    if( /* some condition */ )
    {
        itNext = myMap.erase( itMap ) ;
        // make sure next iteration is correct

        itMap = --itNext;
    }
}
is it safe, or do I have to put checks for itNext == end() and begin() in as well? "Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley
"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley
Agony
Agony
My loops that involve erasing typically go like this:
std::something<something>::iterator i = Container.begin();
while (i != Container.end())
{
if (SomeCondition)
i = Container.erase(i);
else
++i;
}
Thus, I only increment if I didn't erase, since the erase in effect does the increment for me already. However, I'm guessing that doing a decrement when you erase, and then incrementing every time regardless of erasing or not, would work fine on at least some types of containers, such as vectors. I couldn't guarantee anything, though, especially for containers like lists and maps, since incrementing and decrementing iterators is not just simple pointer addition/subtraction. Just to be on the safe side, I wouldn't recommend it.

[edited by - Agony on April 26, 2004 4:02:53 PM]
"We should have a great fewer disputes in the world if words were taken for what they are, the signs of our ideas nly, and not for things themselves." - John Locke o
TheSalmon
TheSalmon
quote:
Original post by Agony
Thus, I only increment if I didn''t erase



Actually, you always increment with that code no matter what since you have ++i in your for loop. Typo I guess?
---Mikael Lax
Agony
Agony
Wow. Typo indeed. Thanks. I''ll edit it. I meant to use a while loop... Silly me.


Most of the greatest evils that man has inflicted upon man have come through people feeling quite certain about something which, in fact, was false.

-Bertrand Russell, Unpopular Essays, "Ideas That Have Harmed Mankind"
"We should have a great fewer disputes in the world if words were taken for what they are, the signs of our ideas nly, and not for things themselves." - John Locke o

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.