Linked Lists using std::forward_list

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?

Abstract art representing computer programming

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.

Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved