Iterating through a map with possible deletions?

Hey everyone,

If I'm looping through all the elements in the map, and at a certain spot I need to stop and remove the element then continue, what's the best way to go about it? I guess I could make a list with all the positions that need to be deleted and then delete once all the elements have been gone over, but I have a feeling that isn't the cleanest way to do it.

Thanks!
if you're looping all the way from beginning to end then just reduce the index by 1 every time you delete an element.

1
2
3
4
5
6
7
8
for ( int i=0; i<myMap.size(); i++ )
{
    if ( someCondition )
    {
        //erase the element
        --i;
    }
}
I tried that before, but I get a memory access error.
1
2
3
4
5
6
7
8
9
10
11
12
13
typedef std::map< K, V >::iterator Iter;

for( Iter i = myMap.begin(); i != myMap.end(); )
{
    if( condition )
    {
         Iter eraseMe = i;
         ++i;
         myMap.erase( i );
    }
    else
        ++i;
}
Last edited on
Or you could erase(i++)
No, erase( i++ ) is undefined.
Why? It makes a copy of the original, increments itself, then returns the copy. It does exactly the same as your code.
¿Shouldn't erase eraseMe ?
Actually, I just googled sequence points and indeed i++ must be evaluated in its entirety, including the post-increment, prior to entering the erase() function, so I stand corrected.

http://en.wikipedia.org/wiki/Sequence_point

When I try that I get an out of range error.

This is the loop I wrote:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
	for ( it=map.begin() ; it != map.end(); )
	{
		if (it->second.second > 0)
		{
			it->second.second-= 10;
			if (it->second.second < 0) {it->second.second =0;}
			it->second.first.SetColor(sf::Color(255,255,255,it->second.second));  
			App->Draw(it->second.first);
			it++;
		}
		else
		{
			Map::iterator eraseMe = it;
			++it;
			map.erase(it);
		}
	}
To do it the way I posted originally, your line 15 is wrong -- it should be map.erase( eraseMe );
OH WOOPS. Wow I'm dumb. Yea I did it your way now and it works great. Thanks!
Topic archived. No new replies allowed.