Home  >  Article  >  Backend Development  >  How are C++ Lambda expressions used in functional programming?

How are C++ Lambda expressions used in functional programming?

WBOY
WBOYOriginal
2024-06-04 20:31:01419browse

C++ Lambda expression is a convenient functional programming tool. The syntax is: [capture_list] (parameter_list) -> return_type { body }Practical example: Sorting: Sorting the word list by string length Filter: Filtering can be 3 List of numbers that are divisible

C++ Lambda 表达式如何用于函数式编程?

C++ Lambda expression: a powerful tool for functional programming

In C++, lambda expression is the most convenient way to pass Code blocks are returned as function arguments or values. Their concise syntax and powerful functionality make them powerful tools for functional programming.

Syntax

lambda expressions have the following syntax format:

[capture_list] (parameter_list) -> return_type { body }
  • capture_list: Capture a list of external variables that can be used inside the lambda body .
  • parameter_list: The parameter list of the lambda function.
  • return_type: Optional return type.
  • body: lambda function body.

Practice Case

1. Sorting Case

Use lambda expression to sort the word list by string length:

#include <vector>
#include <algorithm>

int main() {
  std::vector<std::string> words = {"Hello", "World", "Lambda", "Expression"};

  std::sort(words.begin(), words.end(),
    [](const std::string& a, const std::string& b) {
      return a.size() < b.size();
    });

  for (const auto& word : words) {
    std::cout << word << "\n";
  }
  return 0;
}

Output:

Hello
Lambda
World
Expression

2. Filter case

Filter out the list of numbers that are divisible by 3:

#include <vector>
#include <algorithm>

int main() {
  std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};

  std::vector<int> filteredNumbers;
  std::copy_if(numbers.begin(), numbers.end(),
    std::back_inserter(filteredNumbers),
    [](int number) {
      return number % 3 == 0;
    });

  for (const auto& number : filteredNumbers) {
    std::cout << number << "\n";
  }
  return 0;
}

Output:

3
6
9

The above is the detailed content of How are C++ Lambda expressions used in functional programming?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn