C++第11课 迭代器与仿函数 (三)

1.lambda表达式

/*
    Lambda表达式: 匿名函数  最终得到的结果是一个函数指针
    产生函数指针的同时,对应的函数也已经定义好
    No.1 Lambda表达式的组成部分
    [捕获方式](函数参数) mutable exception ->函数返回值{ 函数体;}
    捕获方式:
        []: 不捕获任何变量
        [=]: 用值的方式捕获
        [&]: 引用的方式
        [this]: this指针捕获
        [&x]: x用引用的方式捕获
        [=,&x]: x用引用,其他用值
*/
int Max(int a, int b)
{
    return a > b ? a : b;
}
//以函数指针为参数的函数中
void print(int a, int b, int(*FUNC)(int, int))
{
    cout << FUNC(a, b) << endl;
}
class Test
{
public:
    Test(string name, int age) :name(name), age(age) {}
    void print()
    {
        cout << "catch this:" << [this]() {return this->name; }() << endl;
        cout << name << endl;
    }
public:
    string name;
    int age;
};
int main()
{
    cout << Max(1, 2) << endl;
    //-----------------------------------------------------------------
    int(*pMax)(int, int) = [](int a, int b) {return a > b ? a : b; };
    cout << pMax(1, 2) << endl;
    //-----------------------------------------------------------------
    cout << [](int a, int b) {return a > b ? a : b; }(1, 2) << endl;
    //-----------------------------------------------------------------
    auto ppMax = Max;
    print(1, 2, ppMax);
    //-----------------------------------------------------------------
    print(1, 2, [](int a, int b) {return a + b; });
    print(1, 2, [](int a, int b) {return a > b ? a : b; });
    int a;
    //-----------------------------------------------------------------
    cout << [](int a, int b)
        mutable noexcept->int {return a > b ? a : b; }(1, 2) << endl;
    //用值的方式和引用区别
    //用值的方式: Lambda调用结果不会应为值的改变而改变
    //用引用: 函数调用的结果会跟着值改变
    //------------------------------------------
    int value = 1;
    [=]() {cout << value << endl; }();    //第一个函数
    value = 123;
    [=]() {cout << value << endl; }();    //第二个函数
    //------------------------------------------
    value = 1;
    auto pPrint = [=]() {cout << value << endl; };
    auto pp = [&]() {cout << value << endl; };
    pPrint();        //打印1
    pp();
    value = 123;
    pPrint();
    pp();
    //-------------------------------------------
    Test mm("mm", 18);
    mm.print();
    return 0;
}

 

posted @ 2021-09-10 19:32  Creature_lurk  阅读(26)  评论(0编辑  收藏  举报