Patrick
Patrick

Reputation: 8300

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

Upvotes: 1

Views: 554

Answers (3)

Cyrille Ka
Cyrille Ka

Reputation: 15538

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

Upvotes: 6

Stack Overflow is garbage
Stack Overflow is garbage

Reputation: 247899

You mean like this?

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

That's the idiomatic way to do it.

Upvotes: 5

Ralph
Ralph

Reputation: 5232

I don't know. Maybe there is. But if there is, then it will be a hell of a statement. Nobody will be able to understand or maintain it. If those two lines do what you want, just stick with them. They are perfectly good.

Upvotes: -2

Related Questions