Single statement method for removing items from a container

Is there one algorithm that removes items from a container, as in the following code?

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

      

+1


source to share


3 answers


The idiomatic way to do this is as jalf said. You can create your own function to make it easier:

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

      

+6


source


Do you mean this?

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

      



This is the idiomatic way to do it.

+5


source


I dont know. Maybe there is. But if there is, then it will be a damn expression. Nobody can understand or support him. If these two lines do what you want, just stick to them. They fit perfectly.

-2


source







All Articles