• C++11 里lambda表达式的学习


    最近看到很多关于C++11的文档,有些是我不怎么用到,所以就略过去了,但是lambda表达式还是比较常用的,其实最开始学习python的时候就觉得lambda这个比较高级,为什么C++这么弱。果然C++增加这个东西。

    语法

    [ capture ] ( params ) mutable exception attribute -> ret { body }      (1)

    [ capture ] ( params ) -> ret { body }                                              (2)

    [ capture ] ( params ) { body }                                                       (3)

    [ capture ] { body }                                                                       (4)

    解释

    capture     -     指定哪些在函数声明处的作用域中可见的符号将在函数体内可见。
                          符号表可按如下规则传入:

                  [=,&b],按引用捕获b,其他局部变量都按值捕获
                  [this],按值捕获了this指针
                  [&] 按引用捕获在lambda表达式所在函数的函数体中提及的全部自动储存持续性变量
                  [=] 按值捕获在lambda表达式所在函数的函数体中提及的全部自动储存持续性变量
                  [] 什么也没有捕获

    params     -     参数列表,与命名函数一样
    ret     -     返回值类型。如果不存在,它由该函数的return语句来隐式决定(或者是void,例如当它不返回任何值的时候)
    body     -     函数体

    例子

    /*[] 什么也没有捕获*/
    auto x = [](){cout<<"Lambda is woring"<<endl;};
    x();
     /*[=] 按值捕获*/ 
    int n=3;
    int m=4;;
    string s="many";
    auto a= [n](string &s) mutable {n++;return s.size()>n;} ; 
    a(s);
    cout<<n<<endl;   //n=3
    
    auto d = [m](string &s) mutable {m++;n++; return s.size()>m;};
    cout<<"m="<<m<<", n="<<n<<endl; //error, n没有捕获

     这个地方不知道为什么必须用mutable,不然编译不过。可能是值捕获的关系吧。

    /*[&] 按引用捕获*/
    int n=3;
    string s="many";
    auto b= [&n](string &s) {n++;return s.size()>n;};
    b(s);
    cout<<n<<endl;   //n=4
    /*[=, &foo] 除了foo引用捕获,其他局部变量全部值捕获*/
    int n=3;
    int m=4;
    string s="many";
    auto c = [=,&n](string &s) mutable {m++;n++; return s.size()>m;};
    c(s);
    cout<<"m="<<m<<", n="<<n<<endl;  //m=4,n=4
    /*[this],按值捕获了this指针 */
    class A
    {
    private:
        int z;
    public:
        A(){z=0;}
        void fun(int m)
        {
            auto a = [this](int m) {return this->z+m;};
            cout<<a(m)<<endl;
        }
    };
    
    int main ()
    {
      A *a =new A();
      a->fun(5);  //5
      return 0;
    }

                          

  • 相关阅读:
    [LeetCode] 19. Remove Nth Node From End of List 移除链表倒数第N个节点
    [LeetCode] 27. Remove Element 移除元素
    [LeetCode] 240. Search a 2D Matrix II 搜索一个二维矩阵 II
    [LeetCode] 74. Search a 2D Matrix 搜索一个二维矩阵
    [LeetCode] 452. Minimum Number of Arrows to Burst Balloons 最少箭数爆气球
    [LeetCode] 312. Burst Balloons 爆气球
    [LeetCode] 257. Binary Tree Paths 二叉树路径
    [LeetCode] 24. Swap Nodes in Pairs 成对交换节点
    [LeetCode] 680. Valid Palindrome II 验证回文字符串 II
    [LeetCode] 234. Palindrome Linked List 回文链表
  • 原文地址:https://www.cnblogs.com/streakingBird/p/3830263.html
Copyright © 2020-2023  润新知