C++ lambda表达式

  lambda 表达式可以方便地构造匿名函数,如果你的代码里面存在大量的小函数,而这些函数一般只被调用一次,可以将他们重构成 lambda 表达式。

  lambda表达式的规范如下:

完整:  [capture] (params) mutable exception attribute->ret{body}

const类型:  [capture] (params)->ret {body}

这种类型的表达式不能改捕获的("capture")l列表的值

省略返回类型:  [capture] (params) {body}

如果lambda代码中包含了return语句,则该lambda表达式的返回值由return 语句的返回类型确定。

[capture] {body}

省略参数列表,类似于无参函数分f()

mutable 修饰符说明lambda 表达式体内的代码可以修改被捕获的变量,并且可以访问被捕获的non-const方法。

exception说明lambda表达式是否跑出异常(noexcept).

attribute 用来声明属性。

另外,capture 指定了在可见域范围内 lambda 表达式的代码内可见得外部变量的列表,具体解释如下:

  • [a,&b] a变量以值的方式呗捕获,b以引用的方式被捕获。
  • [this] 以值的方式捕获 this 指针。
  • [&] 以引用的方式捕获所有的外部自动变量。
  • [=] 以值的方式捕获所有的外部自动变量。
  • [] 不捕获外部的任何变量。

此外,params 指定 lambda 表达式的参数。

 1 #include <vector>
 2 #include <iostream>
 3 #include <algorithm>
 4 #include <functional>
 5  
 6 int main()
 7 {
 8     std::vector<int> c { 1,2,3,4,5,6,7 };
 9     int x = 5;
10     c.erase(std::remove_if(c.begin(), c.end(), [x](int n) { return n < x; } ), c.end());
11  
12     std::cout << "c: ";
13     for (auto i: c) {
14         std::cout << i << ' ';
15     }
16     std::cout << '
';
17  
18     // the type of a closure cannot be named, but can be inferred with auto
19     auto func1 = [](int i) { return i+4; };
20     std::cout << "func1: " << func1(6) << '
'; 
21  
22     // like all callable objects, closures can be captured in std::function
23     // (this may incur unnecessary overhead)
24     std::function<int(int)> func2 = [](int i) { return i+4; };
25     std::cout << "func2: " << func2(6) << '
'; 
26 }

参考文档:http://www.cnblogs.com/haippy/archive/2013/05/31/3111560.html

原文地址:https://www.cnblogs.com/lhwblog/p/6435339.html