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;
    ...
  }
programming/stl.txt · Last modified: 2013/09/19 16:41 (external edit)
 
Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki