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.
Answers to questions are automatically generated and may not have been reviewed.
std::forward_list
This lesson provides an in-depth exploration of std::forward_list
, covering creation, management, and advanced list operations