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

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Iterator Invalidation in std::forward_list
When do iterators become invalidated in a std::forward_list?
Using splice_after() in std::forward_list
How can I transfer elements from one forward_list to another using splice_after()?
Removing Consecutive Duplicates in std::forward_list
How can I remove consecutive duplicate elements from a forward_list?
Merging Sorted Lists in std::forward_list
How can I merge two sorted forward_list objects into one sorted list?
Reversing Elements in std::forward_list
How can I reverse the order of elements in a forward_list?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant