完整表达式
[ capture ] ( params ) mutable exception attribute -> ret { body }
例子
auto func1 = [](int i) { return i+4; };
解释:
[ capture ] 里面的是 capture block 是从 lambda 内的代码可以看见的外部变量, 有几种形式
mutable 修饰符说明 lambda 表达式体内的代码可以修改被捕获的变量,并且可以访问被捕获对象的 non-const 方法。
exception 说明 lambda 表达式是否抛出异常(noexcept), 类似于void f() throw(X, Y)
例子:
std::vector<int> c { 1,2,3,4,5,6,7 };
int x = 5;
c.erase(std::remove_if(c.begin(),
c.end(),
[x](int n) { return n < x; } ), // x 是 capture 到的外部变量
c.end());
std::cout << "c: ";
for (auto i: c) {
std::cout << i << ' ';
}
std::cout << '\n';
[] {std::cout << "Hello from Lambda" << std::endl} (); // 最后的()让该 lambda 立即执行