How to use lambda expressions in C++?

In C++, lambda expressions are anonymous functions that can be used wherever a function object is needed. The basic syntax of a lambda expression is as follows:

[capture list] (parameters) -> return_type {
    // lambda函数体
}

Among them, the capture list specifies the external variables that a lambda function can access; parameters represent the list of parameters; return_type indicates the return type; and the lambda function body is the actual implementation of the function.

Here is a simple example:

#include <iostream>

int main() {
    int a = 5;
    
    auto lambda = [a](int x) -> int {
        return a + x;
    };
    
    std::cout << lambda(3) << std::endl; // 输出8
    
    return 0;
}

In this example, the lambda expression captures the external variable ‘a’, takes a parameter ‘x’, and returns the result of ‘a + x’. Lambda expressions can be called like regular functions, stored in variables, and used as function objects.

Leave a Reply 0

Your email address will not be published. Required fields are marked *