Skip to main content

Interesting properties of iterators

 Erasing in map in a loop.

if you run this code:

Consider 'mp' as map<int,int>

for(auto &it : mp)
{
    a.erase(it.first);
}

This would give you a runtime error as follows:
terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc

This is because when you are erasing it.first from a map and then in the loop you are doing it++ and it do not exist after erasing. So, this loop will work instead:

auto it=a.begin();
while(it!=a.end())
{
  it=a.erase(it);
}


Comments