C++ review notes--Lambda expression

1--Lambda expression

1-1--Basic usage

① [] is used to capture variables, generally used to use and modify external variables, and can be empty;

② (int a, int b) indicates the parameter list, which can be omitted;

③ -> int defines the return type, which can generally be omitted and let the compiler infer it automatically;

④ auto f means to assign the defined lambda expression to the object f, and auto is used to automatically infer the type;

The basic usage is as follows:

#include <iostream>
 
int main(int argc, char *argv[]){

    auto f = [](int a, int b) -> int{
        return a + b;
    };

    std::cout << f(1, 2) << std::endl;
    return 0;
}

1-2--Other usages

① Use and modify external variables

Modify (pass by reference) and use external variables by capturing variables:

#include <iostream>
 
int main(int argc, char *argv[]){

    int M = 10, N = 20;
    auto f = [&M, N](int a, int b){
        std::cout << "N:" << N << std::endl; // 使用外部变量
        M = 30; // 修改外部变量
        return a + b;
    };

    std::cout << f(1, 2) << std::endl;
    std::cout << "M: " << M << std::endl;
    return 0;
}

② Custom variables

Customize variables by capturing variables without appearing outside;

#include <iostream>
 
int main(int argc, char *argv[]){

    int M = 10, N = 20;
    auto f = [&M, N, c=3](int a, int b){
        std::cout << "N:" << N << std::endl; // 使用外部变量
        M = 30; // 修改外部变量
        return (a + b) * c;
    };

    std::cout << f(1, 2) << std::endl;
    std::cout << "M: " << M << std::endl;
    return 0;
}

2--Reference

Clear and easy to understand, one of the best features of modern C++: Lambda expression usage details

Guess you like

Origin blog.csdn.net/weixin_43863869/article/details/131732402