Home  >  Article  >  Backend Development  >  What are the syntax rules for C++ lambda expressions?

What are the syntax rules for C++ lambda expressions?

WBOY
WBOYOriginal
2024-06-01 17:33:001035browse

Lambda expression is an anonymous function, the syntax is as follows: [capture list] (parameter list) -> return type {function body} capture list specifies the variables to be captured from the surrounding environment, parameter list specifies the parameter list, return The type specifies the return type, and the function body defines the function body. Capture variables are captured by reference, and the type can be inferred from the capture list, parameter list, and return type.

C++ Lambda 表达式的语法规则是什么?

Syntax rules for C++ Lambda expressions

A Lambda expression is an anonymous function that allows you to create it without defining an explicit function A callable object. The syntax is as follows:

[capture list] (parameter list) -> return type { function body }

Where:

  • capture list: Specifies a list of variables to be captured from the surrounding environment.
  • parameter list: Specifies the parameter list of the lambda expression.
  • return type: Specify the return type of the lambda expression. Can be omitted, in which case the lambda expression returns void.
  • function body: Defines the function body of the lambda expression.

Here are some examples:

// Capture 变量 x 并返回 x 的平方
auto square = [](int x) { return x * x; };

// 捕获变量 y 并返回 y 的立方
auto cube = [&](int y) { return y * y * y; };

Note:

  • Lambda expressions can be used in C++11 and higher Version.
  • Captured variables in Lambda expressions are captured by reference unless captured as value is explicitly specified.
  • The type of a Lambda expression can be inferred based on the capture list, parameter list, and return type.

Practical case

The following is a simple example using lambda expressions:

#include <iostream>
#include <vector>

using namespace std;

int main() {
  // 使用 lambda 表达式对向量中的每个元素平方
  vector<int> numbers = {1, 2, 3, 4, 5};
  for_each(numbers.begin(), numbers.end(), [](int& num) { num *= num; });

  // 使用 lambda 表达式对向量进行排序
  sort(numbers.begin(), numbers.end(), [](int a, int b) { return a > b; });

  // 打印排序后的向量
  for (int num : numbers) {
    cout << num << " ";
  }
  cout << endl;

  return 0;
}

The above is the detailed content of What are the syntax rules for C++ lambda expressions?. 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