[](){}--C++中的lambda函数(匿名函数)

一、基本形式

[capture](parameters)->return-type {body}
例如:
auto func = [](){ cout << "hello,world"; };

1. “[ ]” -- 捕获说明符,表示一个lambda表达式的开始


  • [ ] -- 不截取任何变量
  • [&] -- 截取外部作用域中所有变量,并作为引用在函数体中使用
  • [=] --截取外部作用域中所有变量,并拷贝一份在函数体中使用
  • [=, &foo] -- 截取外部作用域中所有变量,并拷贝一份在函数体中使用,但是对foo变量使用引用
  • [bar] -- 截取bar变量并且拷贝一份在函数体重使用,同时不截取其他变量
  • [x, &y] -- x按值传递,y按引用传递
  • [this] -- 截取当前类中的this指针。如果已经使用了&或者=就默认添加此选项。

2. "( )" -- 参数列表,即这个匿名的lambda函数的参数

[](const DMatch &m1, const DMatch &m2) { return m1.distance < m2.distance; }

3. "return-type" -- 回类型,如果没有返回类型,则省略

4. "{ }" -- 函数体部分

猜你喜欢

转载自blog.csdn.net/weixin_44884561/article/details/128664564