Jump to content
  • Advertisement
Sign in to follow this  
lride

vector iterator not incrementable

This topic is 2159 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
Advertisement
If iter refers to the final element, vec.pop_back() invalidates iter, making the "iter++" operation erroneous.

Share this post


Link to post
Share on other sites

Never mind, I found a solution

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 erase-remove idiom.

Share this post


Link to post
Share on other sites
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!