Search code examples
c++vectorstlduplicateserase

Can vector erase() function delete two consecutive same elements?


Below is a snippet of my program. I iterate through a vector and try to delete all the element which has the value of three. But after I print the content of the vector,it's 1-2-4-3-5,it still has a number 3. Why? Do we have to deal with iterator specially if we want to delete two consecutive same elements?

int main()
{
    std::vector<int> a = {1, 2, 3, 4, 3, 3, 5}; // a has size 5
    for(auto it=a.begin();it!=a.end();)
    {
        if(*it == 3) it=a.erase(it);
        it++;
    }
    for(auto x:a) cout<<x<<endl;
}

Solution

  • We can break down your example and only look at the last three numbers 3, 3, 5.

    After erasing the first 3, an iterator two the second 3 is returned in

    it = a.erase(it);
    

    But immediately after this it is incremented in

    it++;
    

    and now points to the 5.


    Here you can use the erase-remove-idiom. Example code:

    a.erase(std::remove(a.begin(), a.end(), 3), a.end());