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?
vector iterator not incrementable
If iter refers to the final element, vec.pop_back() invalidates iter, making the "iter++" operation erroneous.
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.
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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement