Erasing elements from a vector

后端 未结 5 696
萌比男神i
萌比男神i 2020-11-21 12:57

I want to clear a element from a vector using the erase method. But the problem here is that the element is not guaranteed to occur only once in the vector. It may be presen

5条回答
  •  北海茫月
    2020-11-21 13:51

    Calling erase will invalidate iterators, you could use:

    void erase(std::vector& myNumbers_in, int number_in)
    {
        std::vector::iterator iter = myNumbers_in.begin();
        while (iter != myNumbers_in.end())
        {
            if (*iter == number_in)
            {
                iter = myNumbers_in.erase(iter);
            }
            else
            {
               ++iter;
            }
        }
    
    }
    

    Or you could use std::remove_if together with a functor and std::vector::erase:

    struct Eraser
    {
        Eraser(int number_in) : number_in(number_in) {}
        int number_in;
        bool operator()(int i) const
        {
            return i == number_in;
        }
    };
    
    std::vector myNumbers;
    myNumbers.erase(std::remove_if(myNumbers.begin(), myNumbers.end(), Eraser(number_in)), myNumbers.end());
    

    Instead of writing your own functor in this case you could use std::remove:

    std::vector myNumbers;
    myNumbers.erase(std::remove(myNumbers.begin(), myNumbers.end(), number_in), myNumbers.end());
    

    In C++11 you could use a lambda instead of a functor:

    std::vector myNumbers;
    myNumbers.erase(std::remove_if(myNumbers.begin(), myNumbers.end(), [number_in](int number){ return number == number_in; }), myNumbers.end());
    

    In C++17 std::experimental::erase and std::experimental::erase_if are also available, in C++20 these are (finally) renamed to std::erase and std::erase_if (note: in Visual Studio 2019 you'll need to change your C++ language version to the latest experimental version for support):

    std::vector myNumbers;
    std::erase_if(myNumbers, Eraser(number_in)); // or use lambda
    

    or:

    std::vector myNumbers;
    std::erase(myNumbers, number_in);
    

提交回复
热议问题