Jump to content

  • Log In with Google      Sign In   
  • Create Account

vector iterator not incrementable


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
6 replies to this topic

#1 lride   Members   -  Reputation: 633

Like
0Likes
Like

Posted 23 November 2012 - 10:49 PM

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, 23 November 2012 - 10:53 PM.

An invisible text.

Sponsor:

#2 e‍dd   Members   -  Reputation: 2105

Like
2Likes
Like

Posted 23 November 2012 - 10:53 PM

If iter refers to the final element, vec.pop_back() invalidates iter, making the "iter++" operation erroneous.

#3 lride   Members   -  Reputation: 633

Like
0Likes
Like

Posted 23 November 2012 - 11:00 PM

what can I do to solve this?
An invisible text.

#4 lride   Members   -  Reputation: 633

Like
-2Likes
Like

Posted 23 November 2012 - 11:17 PM

Never mind, I found a solution
An invisible text.

#5 Álvaro   Crossbones+   -  Reputation: 13901

Like
3Likes
Like

Posted 23 November 2012 - 11:25 PM

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.

#6 e‍dd   Members   -  Reputation: 2105

Like
0Likes
Like

Posted 23 November 2012 - 11:53 PM

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.

#7 SiCrane   Moderators   -  Reputation: 9668

Like
1Likes
Like

Posted 24 November 2012 - 07:25 AM

Note that if order isn't important, std::partition() may be faster than std::remove_if().




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS