Browse - Programming Tips - How do I selectively delete items from a STL vector?
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
p = v.erase(p); // calls the destructor
// use the iterator returned by erase
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()
But note that remove_if() does not call destructors or decrease size()
so I never find it much use.