2.Lambda expressions
lambda表达式
规则
[]- captures nothing.
[=]- capture local objects (local variables, parameters) in scope by value.
[&]- capture local objects (local variables, parameters) in scope by reference.
[this]- capturethisby reference.
[a, &b]- capture objectsaby value,bby reference.
int x = 1;
auto getX = [=] { return x; };
getX(); // == 1
auto addX = [=](int y) { return x + y; };
addX(1); // == 2
auto getXRef = [&]() -> int& { return x; };
getXRef(); // int& to `x`除非使用引用,否则不能在lambda里面修改传递的变量,默认是const的,除非加了mutable关键字,如下:
int x = 1;
auto f1 = [&x] { x = 2; }; // OK: x is a reference and modifies the original
auto f2 = [x] { x = 2; }; // ERROR: the lambda can only perform const-operations on the captured value
// vs.
auto f3 = [x]() mutable { x = 2; }; // OK: the lambda can perform any operations on the captured value使用场景
stl sort 自定义排序规则
函数内部的简易函数调用
最后更新于
这有帮助吗?