参考:
https://www.cnblogs.com/DswCnblog/p/5629165.html
https://en.cppreference.com/w/cpp/language/lambda
-
完整格式:[
captures
] (params
)specifiers
exception
attr
->ret
{body
}captures: 捕获列表
params:传入参数
specifiers:mutable
,constexpr
,consteval
exception: 指定lambda可以throw的exception
attr:函数的属性, 如[[ noreturn]]
,[[deprecated("because")]]
ret:返回值
body:函数体 -
捕获列表:用于捕获lambda外部变量,可以按不同的方式捕获
捕获方式 说明 [&] 默认按引用捕获用到的变量(by reference) [=] 默认按值捕获用到的变量(by copy) [this] 按引用捕获当前对象 [*this] 按值捕获当前对象 [&x] 按引用方式捕获x变量 [x] 按值捕获x变量 [=, &x] 按引用捕获x变量,其余变量按值捕获 [&, x] 按值捕获x变量,其余变量按引用捕获 -
exception可以这样声明:
https://visualstudiomagazine.com/articles/2012/06/18/cplus-lambda-expressions.aspx
// 表明lambda可能throws runtime_error. auto myLambda = []() throws(runtime_error) -> bool { ... }; // 表明lambda不会throw exceptions. auto myLambda = []() throws() -> bool { ... }; // 表明lambda可能throw任何exception. auto myLambda = []() -> bool { ... };
-
例子:
vector中找某个符合条件的值,用find_if函数,其中第三个参数使用lambda表达式class A { public: A(std::string name): name_(name) {}; std::string name() { return name_; }; private: std::string name_; }; int main() { std::vector<A> list; list.emplace_back("xxx"); std::string value_to_find("xxx"); auto iter = std::find_if(list.begin(), list.end(), [value_to_find] (const A & obj) -> bool { return obj.name() == value_to_find; }); }