Table of Contents

STL

Erasing elements in a loop

Map

Erasing an element does not invalidate other iterators.

  bool erase_i;
  for(std::map<int,int>::iterator i = myMap.begin(); i != myMap.end(); erase_i ? myMap.erase(i++) : ++i)
  {
    erase_i = false;
    ...
    if (want_erase) erase_i = true;
    ...
  }

Vector, List

Erasing an element do invalidate other iterators.

  bool erase_i;
  for(std::vector<int>::iterator i = myVec.begin(); i != myVec.end(); erase_i ? i = myVec.erase(i) : ++i)
  {
    erase_i = false;
    ...
    if (want_erase) erase_i = true;
    ...
  }