c++11之lambda

  • 基本测试代码
      1. /************************************************************************/
      2. /* 测试lambda */
      3. /************************************************************************/
      4. #include<iostream>
      5. #include<functional>
      6. class A
      7. {
      8. public:
      9. int i_ =0;
      10. void func(int x,int y)
      11. {
      12. auto ff =[this, x, y]{return i_ + x + y;};//捕获了this,否则没法使用类成员变量
      13. }
      14. };
      15. int main()
      16. {
      17. //[]内为要捕获的外部变量
      18. auto f1 =[](int a)->int{return a;};//这是完整的写法,带参数列表,带返回值
      19. auto f2 =[](int a){return a +1;};//省略了返回值类型,这个是显而易见的
      20. auto f3 =[]{return2;};//没有参数这可以省略不写
      21. int a =0;
      22. auto f =[=]{return a;};//捕获所有变量的值,没法修改a,只是传递了值
      23. a++;
      24. std::cout << f()<< std::endl;
      25. //输出为0
      26. int b =2;
      27. auto f4 =[&b]{return++b;};//捕获了变量b的引用,对其修改
      28. std::cout << f4()<< std::endl;
      29. //配合bind
      30. std::function<int(int)> fr =[](int a){return a +9;};
      31. auto fr2 = std::bind(fr,4);
      32. auto fr3 = std::bind([](int a){return a;},555);
      33. std::cout << fr2()<< std::endl;
      34. std::cout << fr3()<< std::endl;
      35. }
       





原文地址:https://www.cnblogs.com/dongdongweiwu/p/4743651.html