In C++, std::list::remove_if() erases every element for which a test function (a predicate) returns true. You write the test as a lambda or a normal function.
Like remove(), the list member erases the elements itself, so you do not need a separate erase() call. Include <list> to use it.
This is a member of std::list<T>, a doubly linked list. Every element lives in its own node with a link to the previous and the next node, so a list can insert and erase anywhere quickly once you hold an iterator. It has no access by index, so l[i] does not exist.
Syntax
Call remove_if with a function that takes one element and returns true for elements that should be erased.
C++
l.remove_if([](int x) { return x % 2 == 0; }); // erase evens
auto n = l.remove_if(pred); // C++20: count
Call
What it does
l.remove_if(pred)
Calls pred(element) for each element and erases it when the result is true.
auto n = l.remove_if(pred)
In C++20 and later, the number of erased elements is returned.
If you only need to compare with one fixed value, remove(value) is shorter.
Library declarations
C++
template<class UnaryPredicate>
void remove_if(UnaryPredicate p); // before C++20
template<class UnaryPredicate>
size_type remove_if(UnaryPredicate p); // since C++20
Parameters
Parameter
Description
p
Required. A function, lambda, or function object. It receives one element and returns true if that element should be erased.
Return Value
Return Value
Description
size_type (C++20)
The number of elements that were erased. Before C++20 the function returns void.
C++ Examples
Example 1 — remove_if() with a Lambda
Erase every even number from a list of eight numbers.
C++
#include <iostream>
#include <list>
int main() {
std::list<int> l = {1, 2, 3, 4, 5, 6, 7, 8};
l.remove_if([](int x) { return x % 2 == 0; });
for (int n : l) {
std::cout << n << ' ';
}
std::cout << "(size " << l.size() << ")\n";
return 0;
}
Output
1 3 5 7 (size 4)
How It Works
The lambda [](int x) { return x % 2 == 0; } returns true for even numbers.
remove_if() calls it once for every element and erases the nodes where the answer is true.
Four odd numbers are left, 1 3 5 7, and size() already shows 4.
Example 2 — remove_if() with a Captured Limit
A lambda can use a variable from outside. Here the limit is stored in limit.
C++
#include <iostream>
#include <list>
int main() {
std::list<int> l = {10, 60, 30, 80, 50};
int limit = 50;
l.remove_if([limit](int x) { return x > limit; });
for (int n : l) {
std::cout << n << ' ';
}
std::cout << '\n';
return 0;
}
Output
10 30 50
How It Works
[limit] in the lambda brackets copies the variable limit into the lambda, so the test can use it.
The test x > limit is true for 60 and 80, so those two nodes are erased.
The value 50 is kept, because 50 > 50 is false. The result is 10 30 50.