0

I'm trying to delete all entries in a map where value == 50 for any key.

This code is working fine for me.

 while (itr != mymap.end())
 {
    if ((*itr).second == 50)
        mymap.erase(itr++);
     else
        itr++;

 }

But this code is giving run time error.

while (itr != mymap.end())
{
    if ((*itr).second == 50)
    {    
        mymap.erase(itr);
        itr++
    }
    else
        itr++;

}

My doubt is aren't both logic is same? why run time error in second case?

Devesh Agrawal
  • 8,982
  • 16
  • 82
  • 131
  • 2
    In the second case you're incrementing an invalid iterator (because you just deleted the item it points to). Consider using [erase/remove idiom](http://stackoverflow.com/questions/1038708/erase-remove-contents-from-the-map-or-any-other-stl-container-while-iterating) – Borgleader Jan 11 '15 at 17:07
  • what is happening in the first case?? same, deleting and incrementing? right? – Devesh Agrawal Jan 11 '15 at 17:11
  • No, the increment happens first, but it++ returns the original value (unlike ++it) so you delete the right item but the iterator already points to the next one. – Borgleader Jan 11 '15 at 17:11
  • @Borgleader, note that `remove_if` is not available for map containers since it is not possible to move elements to the end of the container in the case of map. – nimrodm Jan 11 '15 at 18:51

1 Answers1

3

No, the logic is not the same. In the first case the iterator is postincremented before erasing the element when it is a valid iterator. In the second case the iterator is postincremented after erasing the element when it is an invalid iterator.

The common approach to this operation is the following

while ( itr != mymap.end() )
{
    if ( (*itr).second == 50 )
        itr = mymap.erase( itr );
     else
        itr++;
}

According to the C++ Standard (23.2.4 Associative containers)

9 The insert and emplace members shall not affect the validity of iterators and references to the container, and the erase members shall invalidate only iterators and references to the erased elements.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335