vector iterator not incrementable

Started by
5 comments, last by SiCrane 11 years, 5 months ago
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?
An invisible text.
Advertisement
If iter refers to the final element, vec.pop_back() invalidates iter, making the "iter++" operation erroneous.
what can I do to solve this?
An invisible text.
Never mind, I found a solution
An invisible text.

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.
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.
Note that if order isn't important, std::partition() may be faster than std::remove_if().

This topic is closed to new replies.

Advertisement