Dave's Brain

Browse - programming tips - vector erase

Date: 2005Jun8

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

Add a comment

Sign in to add a comment
Copyright © 2008, dave - Code on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License.