c++ lambda

https://www.jianshu.com/p/d686ad9de817

测试代码:

#include <iostream>
#include <memory>
using namespace std;

int main(){
    int x=3;
    auto add1 = [x](int a, int b) -> int { int res= a + b - x; return res; };
    auto add2 = [&x](int a, int b){ x = a + b -x;return x; };
    cout<<add1(1,2)<<endl; // 0
    cout<<add2(1,2)<<endl; // 0
    auto y = [&r = x,x=x+1](){r += 2;return x*x;};
    auto z = [r = 3](){return r-3;};
    cout<<y()<<endl; // 1
    cout<<z()<<endl; // 0
    cout<<x<<endl;   // 2

    auto myPi = make_unique<double>(3.1415);

    auto circle_area = [&myPi](double r) { return *myPi * r * r; };
    cout << circle_area(3.0) << endl; // 3.1415*9
    cout << *myPi <<endl;
    auto circle_area1 = [pi = move(myPi)](double r) { return *pi * r * r; };
    cout << circle_area1(2.0) << endl; // 3.1415*4
    //cout << *myPi <<endl; // segment fault error

    auto add = [](auto x, auto y) { return x + y; };

    int x1 = add(2, 3);   // 5
    double y1 = add(2.5, 3.5);  // 6.0

    return 0;
}
posted @ 2020-08-05 16:18  mangoCzp  阅读(108)  评论(0编辑  收藏  举报