Possible Duplicate:
How to filter items from a std::map?
What happens if you call erase() on a map element while iterating from begin to end?
I have map of objects and i want to iterate over it and remove 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 in this way?
In case of
std::mapiterators and references to the erased elements are invalidated [23.1.2/8]. Your code uses the iterator after it has been invalidated, this results in an Undefined Behavior. In order to avoid this Undefined behavior the iterator needs to be incremented before it gets invalidated in theerase()call.You need to use:
Note that here
it++incrementsitso that it refers to the next element but yields a copy of its original value. Thus,itdoesn’t refer to the element that is removed whenerase()is called.