Sign in to follow this  
unknownProdigy

iterator issue

Recommended Posts

unknownProdigy    160
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 this post


Link to post
Share on other sites
Telastyn    3777
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 this post


Link to post
Share on other sites
Xai    1848
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 this post


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

Share this post


Link to post
Share on other sites
Trap    684
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 this post


Link to post
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]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this