c++匿名表达式

C++ 11 Lambda表达式 

C++11中的匿名函数(lambda函数,lambda表达式)

https://gitlab.com/yzzy/modern-cpp/-/blob/main/c16_lambda/main.cpp

[](int x, int y) { return x + y; } // 隐式返回类型
[](int& x) { ++x; }   // 没有return语句 -> lambda 函数的返回类型是'void'
[]() { ++global_x; }  // 没有参数,仅访问某个全局变量
[]{ ++global_x; }     // 与上一个相同,省略了()
// 显示指定返回类型
[](int x, int y) -> int { int z = x + y; return z; }

 

匿名函数的使用
int aa = 123;
    auto f = [aa]{cout << aa << endl;};
    f();   // 输出123

    // 或通过函数体后面的()传入参数
    auto x = [](int aa){return aa;}(123); 
    cout << "x: " << x << endl;



    auto f1 = [](){cout << "abc" <<endl;};
    f1();                   // abc

    int a1{10};
    auto f2 = [a1](){cout << "a1: " << a1 <<endl;};
    f2();                   // a1: 10

    int b{20};
    auto f3 = [&b, a1](){
        cout << "a1: " << a1 << endl;
        cout << "b: " << b << endl;
        b += 1;
    };
    f3();                   // b: 20
    cout << "after b: " << b << endl;    // after b: 21


    int a{10};
    int b{20};

    auto func2 = [=]()
    {
        cout << "a :" << a << endl;
        cout << "b :" << b << endl;
    };

    auto func3 = [&]()
    {
        cout << "a :" << a << endl;
        cout << "b :" << b << endl;
        a++;
        b++;
    };

    func2();
    func3();

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2022-11-15 23:15  7aughing  阅读(39)  评论(0编辑  收藏  举报