What happens with `map::iterator` when i remove entry from map?
c++, dictionary, iterator
Solution
In case of `std::map` iterators 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 the `erase()` call.
You need to use:
for(it = m.begin(); it != m.end(); ) {
if( condition )
m.erase(it++);
else
++it;
}
Note that here `it++` increments `it` so that it refers to the next element but yields a copy of its original value. Thus, `it` doesn't refer to the element that is removed when `erase()` is called.
Problem
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?