I want to erase certain elements while iterating a vector, but the below code results in a "vector iterator not incrementable" assertion failure.
for(auto iter=vec.begin(); iter!=vec.end(); ++iter)
{
if((*iter).isDead())
{
std::swap(*iter, vec.back());//swap with the back
vec.pop_back(); //erase the element
}
}
What is wrong with this code?
To delete single element from a vector using erase() function, pass the iterator of element to it like erase(it). It will delete the element pointed by the iterator the it variable. To delete multiple elements from a vector using erase() function, pass the iterator range to it like erase(start, end-1).
Every iterator and reference after the point of erasing is invalidated. Only the iterators and references to the erased element is invalidated. Only iterators and references to the erased elements are invalidated.
All the elements of the vector are removed using clear() function. erase() function, on the other hand, is used to remove specific elements from the container or a range of elements from the container, thus reducing its size by the number of elements removed.
You should increment the iterator only if you don't remove any element at that iteration:
for(auto iter=vec.begin(); iter!=vec.end();)
{
if((*iter).isDead())
{
std::swap(*iter, vec.back());//swap with the back
vec.pop_back(); //erase the element
}
else
++iter;
}
Or even better, replace the whole loop with remove_if
:
vec.erase(std::remove_if(vec.begin(), vec.end(),
std::bind(&ValueType::isDead, _1)), vec.end());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With