Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erasing element in a vector while iterating using swap-and-pop

Tags:

c++

vector

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?

like image 276
kiwon Avatar asked Dec 10 '12 15:12

kiwon


People also ask

How do you delete from a vector while iterating through it?

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).

What happens to iterator after erase?

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.

Can we remove element from vector?

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.


1 Answers

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());
like image 138
Yakov Galka Avatar answered Sep 29 '22 15:09

Yakov Galka