Home > Article > Backend Development > What are the syntax rules for C++ lambda expressions?
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.
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:
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:
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!