Sign in to follow this  
lride

vector iterator not incrementable

Recommended Posts

lride    674
This code gives assertion failure-"vector iterator not incrementable"
I'm trying to remove even numbers while iterating.
I can't use remove_if

[source lang="cpp"] std::vector<int> vec;
for(int i=1; i<=20; ++i)
vec.push_back(i);

for(auto iter=vec.begin(); iter!=vec.end(); ++iter)
{
if(*iter%2==0){
std::swap(*iter, vec.back());//swap-and-pop
vec.pop_back();
}
}[/source]

isn't iter!=vec.end() enough? Edited by lride

Share this post


Link to post
Share on other sites
alvaro    21263
[quote name='lride' timestamp='1353734268' post='5003676']
Never mind, I found a solution
[/quote]
That's not very helpful. If somebody finds this thread in the future because they have a similar problem, you will not have helped them much. So please explain what your solution is.

If you happen to be that hypothetical web searcher, the recommended solution for this is the [url="http://en.wikipedia.org/wiki/Erase-remove_idiom"]erase-remove idiom[/url].

Share this post


Link to post
Share on other sites
the_edd    2109
It appears as if you're trying to remove even numbers from the vector. However, note that at any point in time, vec.back() can also be even, so trying to do this with swap-and-pop is futile since you can end up swapping one even number for another before advancing to the next element.


For example, given your input set, you will end up with '20' at index 1, even if the iterator invalidation problem can be addressed.

+1 for erase-remove.

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