What happens to `map :: iterator` when I delete a record from a map?

Possible duplicate:
How to filter elements with std :: map? What happens if you call erase () on a map element, iterating from start to finish?

I have an object map and I want to iterate over it and delete some entries.

typedef std::map<A,B> MapT;
MapT m;
MapT::iterator it;

for(it = m.begin(); it != m.end(); it++ ) {
    if( condition ) m.erase(it);
}

Can I do it this way?

+3
source share
2 answers

In the case, std::mapiterators and references to erased elements are invalid [23.1.2 / 8]. Your code uses an iterator after it is invalidated, this leads to Undefined Behavior . To avoid this Undefined behavior, the iterator needs to increment it before it becomes invalid in the call erase().

:

for(it = m.begin(); it != m.end(); ) {
    if( condition )
        m.erase(it++);
    else
        ++it;
}

, it++ it , , . , it , erase().

+8

, MapT std::map, . (erase ) :

MapT m;
MapT::iterator it;

for(it = m.begin(); it != m.end();)
{
    if(condition)
    {
       MapT::iterator tmp = it++;
       m.erase(tmp);
    }
    else
    {
       ++it;
    } 
}
+2

All Articles