I've got a container and would like to erase elements based on a predicate. Erase_if sounds familiar, but I can't find it in C++. What's the name and where is it defined? I'd like to use it with a lambda in VS10.
+4
A:
You're probably looking for std::remove_if
, in a pattern such as:
vec.erase(std::remove_if(vec.begin(), vec.end(), predicate), vec.end());
Victor Nicollet
2010-08-06 15:07:52
And you'll find it in `<algorithm>`, along with the other standard algorithms.
Mike Seymour
2010-08-06 16:07:38
A:
There is a list::remove_if
, but not for all container classes. remove_if
also exists as a algorithm, which can be used with the iterators you can get from begin()
and end()
.
Arne Burmeister
2010-08-06 15:10:35
+1
A:
I'm guessing you're thinking of remove_if
which takes a predicate to determine if the element ought to be removed.
remove_if
returns an iterator pointing to the beginning of the elements to remove in the container. To actually remove them you need to use erase
:
container.erase(remove_if(container.start(), container.end(), pred), container.end())
Either that or perhaps you mistakenly recalled the copy_if
algorithm? Which somehow got left out of the standard but was written about - and implemented - in Effective STL.
MattyT
2010-08-06 15:19:59