# iterator issue

## Recommended Posts

When I use the erase() function for vectors, and pass an iterator, what will be the value of the iterator be after erase() is called. The same or the one that comes next? vector::iterator vIterator; v.erase(vIterator);

##### Share on other sites
I can't guarantee this is correct, as I've never really used the STL, but I peruse the forums a ton...:

It will be the same [what you just erased] and is now useless. If I read and remember correctly of course.

##### Share on other sites
here's a quote from http://www.pottsoft.com/home/stl/stl.htmlx:

"Be careful if you erase() or insert() elements in the middle of a vector. This can invalidate all existing iterators. To erase all elements in a vector use the clear() member function."

##### Share on other sites
According to the STL specs, every iterator assigned previously to calling erase() will become invalid. So in your example, this also includes 'vIterator'.

##### Share on other sites
Simple anwser:
use vIterator = v.erase(vIterator);
then vIterator points to the element after the erased one. And the same code will work for std::list too.

##### Share on other sites
According to 23.2.4.3.3 of the standard:

Quote:
 "Invalidates all iterators and references after the point of the erase."

If you want to safely get the iterator to the next element, use the returned iterator from your erase operation:

vector::iterator vIterator;vIterator = v.erase( vIterator ); // safe and portable

Edit:

After rereading, I'm not sure if the standard means that all iterators and references become invalid if they refer to elements after the one being erased or if they mean that all iterators and references you have, wherever they are in the vector, become invalid after you call the erase function. The difference comes with what the standard means when they say "point," as it can be interpretted as the time you call the function or the place in the vector on which the erase function operates.

[Edited by - Polymorphic OOP on February 14, 2005 7:31:09 PM]

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628318
• Total Posts
2982044

• 9
• 9
• 13
• 11
• 15