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] - capture this by reference.

  • [a, &b] - capture objects a by value, b by 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`
  1. 除非使用引用,否则不能在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 自定义排序规则

函数内部的简易函数调用

最后更新于

这有帮助吗?