Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Perl

Idiom #247 Filter list in-place

Remove all the elements from list x that don't satisfy the predicate p, without allocating a new list.
Keep all the elements that do satisfy p.

For languages that don't have mutable lists, refer to idiom #57 instead.

@x = grep { p($_) } @x;
#include <list>
#include <functional>
std::list<Foo> x;
x.remove_if(std::not_fn(p));

C++17 or later
Also works if x is an std::forward_list

New implementation...