Dave's Brain

Browse - 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.

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.