Using Lambda Expressions with remove_if()
in std::forward_list
How can I use a lambda expression as the predicate for remove_if()
in a forward_list
?
The remove_if()
member function in std::forward_list
accepts a unary predicate that returns true
for the elements to be removed. We can use a lambda expression to define this predicate inline.
Here's an example that removes all even numbers from a forward_list
:
#include <forward_list>
#include <iostream>
int main() {
std::forward_list<int> list{
1, 2, 3, 4, 5, 6};
list.remove_if([](int i) {
return i % 2 == 0; });
for (int i : list) {
std::cout << i << ' ';
}
}
1 3 5
The lambda expression [](int i) { return i % 2 == 0; }
returns true
for even numbers, so remove_if()
removes all even numbers from the list.
We can also capture variables in the lambda:
#include <forward_list>
#include <iostream>
int main() {
std::forward_list<int> list{1, 2, 3, 4, 5, 6};
int threshold = 3;
list.remove_if([threshold](int i) {
return i > threshold; });
for (int i : list) {
std::cout << i << ' ';
}
}
1 2 3
Here, the lambda captures threshold
by value and removes all elements greater than threshold
.
Lambda expressions provide a convenient way to define simple predicates directly at the call site, improving readability and reducing the need for separate named functions.
Linked Lists using std::forward_list
This lesson provides an in-depth exploration of std::forward_list
, covering creation, management, and advanced list operations