Home  >  Article  >  Backend Development  >  What are the usage scenarios of lambda expressions in C++ functions?

What are the usage scenarios of lambda expressions in C++ functions?

王林
王林Original
2024-04-19 14:45:02926browse

Lambda expressions are anonymous functions that can be used to simplify code, as callback functions, or parameterized functions. The advantages include simplified code, reduced redundancy, and increased flexibility.

C++ 函数的 lambda 표达式的使用场景是什么?

Usage scenarios of lambda expressions in C functions

lambda expression is an anonymous function that can be defined within the function body and use. Unlike ordinary functions, lambda expressions have no name and can only be used within the scope in which it is defined.

Usage scenarios:

  1. Simplify code: Use lambda expressions to simplify code with simple functions. For example, the following code uses a lambda expression to increment each element in the list by 1:
#include <iostream>
#include <vector>

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

  // 使用 lambda 表达式增加每个元素
  std::for_each(numbers.begin(), numbers.end(), [](int& n) { n++; });

  // 打印增加后的列表
  for (int num : numbers) {
    std::cout << num << " ";
  }

  return 0;
}
  1. As a callback function: lambda expressions can be passed as callback functions to Other functions. For example, the following code uses a lambda expression as a callback function to sort the elements in a list:
#include <iostream>
#include <vector>
#include <algorithm>

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

  // 使用 lambda 表达式对列表排序
  std::sort(numbers.begin(), numbers.end(), [](int a, int b) { return a < b; });

  // 打印排序后的列表
  for (int num : numbers) {
    std::cout << num << " ";
  }

  return 0;
}
  1. Function parameterization: lambda expressions can be used to parameterize functions . For example, the following code defines a function that receives a lambda expression and performs an iterative operation:
#include <iostream>
#include <vector>

void for_each(std::vector<int>& numbers, std::function<void(int&)> operation) {
  for (int& num : numbers) {
    operation(num);
  }
}

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

  // 使用 lambda 表达式参数化 for_each 函数
  for_each(numbers, [](int& n) { n *= n; });

  // 打印平方后的列表
  for (int num : numbers) {
    std::cout << num << " ";
  }

  return 0;
}

Advantages:

  • Simplified code
  • Reduce redundancy
  • Improve flexibility

The above is the detailed content of What are the usage scenarios of lambda expressions in C++ functions?. 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