Search code examples
c++stlerase-remove-idiom

Single statement method to remove elements from container


Is there a single algorithm that removes elements from a container as happens in the following code?

vec_it = std::remove_if( vec.begin(), vec.end(), pred );
vec.erase( vec_it, vec.end() );

Solution

  • The idiomatic way to do it is like jalf has said. You can build your own function to do that more easily:

    template<typename T, typename Pred> void erase_if(T &vec, Pred pred)
    {
        vec.erase(std::remove_if(vec.begin(), vec.end(), pred), vec.end());
    }
    

    So you can use

    std::vector<int> myVec;
    // (...) fill the vector. (...)
    erase_if(myVec, myPred);