Programming Tips - How do I selectively delete items from a STL vector?

Date: 2005Jun8 Language: C++ Keywords: delete, remove, erase, array Q. How do I selectively delete items from a STL vector? A. If you just loop normally the iterator will become invalid. One solution is to use the iterator returned by erase() like this:
for (V::iterator p = v.begin(); p != v.end();) // no p++ here { if (NeedsDelete(*p)) { p = v.erase(p); // calls the destructor // use the iterator returned by erase } else { p++; // only increment when not deleting } }
The Borland C++ 5.02 erase() does not return a iterator but you are safe to just to replace "p = v.erase(p)" with just "v.erase(p)" See also remove_if() http://www.google.com/search?q=STL+remove_if But note that remove_if() does not call destructors or decrease size() so I never find it much use.