【C++编程】Lambda表达式

 ISO C++ 标准展示了作为第三个参数传递给 std::sort() 函数的简单 lambda:

 

 1 #include <algorithm>
 2 #include <cmath>
 3 
 4 void abssort(float* x, unsigned n) {
 5     std::sort(x, x + n,
 6         // Lambda expression begins
 7         [](float a, float b) {
 8             return (std::abs(a) < std::abs(b));
 9         } // end of lambda expression
10     );
11 }

此图显示了 lambda 的组成部分:

 

 

  1. 捕获子句 (也称为 c + + 规范中的 引导 。 )

  2. 参数列表 可有可无. (也称为 lambda 声明符)

  3. 可变规范 可有可无.

  4. 异常规范 可有可无.

  5. 尾随-返回类型 可有可无.

  6. lambda 体

 1. 例子:代码来源

 1 #include <iostream>
 2 using namespace std;
 3 
 4 struct Foo
 5 {
 6   int x = 1;
 7 
 8   void foo(int x)
 9   {
10     auto f = [x, this] { cout << x << endl; };
11     f();
12   }
13 };
14 
15 int main()
16 {
17   Foo foo;
18   foo.foo(2); // 2
19 }

 

2. 例子

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class test
 5 {
 6 public:
 7   void hello()
 8   {
 9     cout << "test hello!n";
10   };
11   void lambda()
12   {
13     auto fun = [this] { // 捕获了 this 指针
14       this->hello();    // 这里 this 调用的就是 class test 的对象了
15     };
16     fun();
17   }
18 };
19 
20 int main()
21 {
22   test t;
23   t.lambda();
24 }

 

posted @ 2021-03-16 22:58  苏格拉底的落泪  阅读(66)  评论(0编辑  收藏  举报