C The standard syntax for writing function Lambda expressions is: [capture](parameters) -> return_type { // Function body}, where capture is the capture of external variables, parameters is the function parameters, and return_type is the function return value type. Its types are divided according to the capture list and parameter list: capture all external variables, no parameters: auto type; capture specific external variables, no parameters: auto type (can be reduced); no capture, parameters: function type. Lambda expressions are used to create temporary function objects, which can be assigned to variables or function pointers, or passed directly as arguments.
C function Lambda expression writing specification
Syntax:
[capture](parameters) -> return_type { // 函数体 }
Among them:
: Capture external variables, optional, default is
[&] (capture all external variables)
: function parameters, optional
: function return value type, optional
Lambda expression type:
Lambda expressions belong to the anonymous function type. Its type depends on the capture list and parameter list: Type
Type (can be reduced)
Type
Usage specifications:
pointer in Lambda expressions points to the context in which they were created.
Actual case:
// 捕获所有外部变量,无参数 auto lambda1 = []() { // 可以访问外部变量 std::cout << "Lambda 1: " << x << std::endl; }; // 捕获特定外部变量,无参数 int x = 10; auto lambda2 = [x]() { // 只可以访问捕获的外部变量 x std::cout << "Lambda 2: " << x << std::endl; }; // 无捕获,有参数 auto lambda3 = [](int y) { // 没有捕获外部变量,y 为函数参数 std::cout << "Lambda 3: " << y << std::endl; }; int main() { lambda1(); lambda2(); lambda3(20); return 0; }
Output:
Lambda 1: 10 Lambda 2: 10 Lambda 3: 20
The above is the detailed content of What are the writing specifications for function lambda expressions in C++?. For more information, please follow other related articles on the PHP Chinese website!