Search code examples
c++dictionaryundefined-behaviorerase

Is it safe to invoke std::map::erase with std::map::begin?


We (all) know, erasing an element, pointer by an iterator invalidates the iterator, for example:

std::map< .. > map_;
std::map< .. >::iterator iter;
// ..
map_.erase( iter ); // this will invalidate `iter`.

But, what about:

map_.erase( map_.begin() );

is this safe? Will map_.begin() be a valid iterator, pointing to the (new) first element of the map?

"test it" is not a solution.


Solution

  • begin() is not an iterator but returns an iterator. After erasing the first element, begin()returns another (valid) iterator.

     std::map<int, int> m;
     m[1] = 2;
     m[2] = 3;
     m.erase(m.begin()); // <- begin() points to 1:2
     std::cout << m.begin()->second; // <- begin() points to 2:3 now