1

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() );
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
Patrick
  • 8,175
  • 7
  • 56
  • 72

3 Answers3

6

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);
Cyrille Ka
  • 15,328
  • 5
  • 38
  • 58
  • Very neat. Obvious when you see it but wouldn't have thought of it myself. I think I might stick with Jalf's method as you can see what is being used but I'm probably just being a wimp... – Patrick Nov 28 '08 at 16:36
5

You mean like this?

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

That's the idiomatic way to do it.

jalf
  • 243,077
  • 51
  • 345
  • 550
  • This is still an algorithm plus a member function call, not a single algorithm call. I would not regard this as improvement over the original suggestion. – Ralph Nov 28 '08 at 17:01
  • True. The thread title asks for a single *statement* though, and this version lives up to that requirement. But yeah, there's no built-in single function that has the desired effect, but it's easy to compose yourself, like ckarmann's answer shows. – jalf Nov 28 '08 at 17:17
-2

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.

Ralph
  • 5,154
  • 1
  • 21
  • 19