版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_38126105/article/details/82817303
c++11中引入了lambda,允许inline函数被定义用作一个参数,或者一个local对象。lambda的引入改变了C++标准库的用法,主要用作搭配STL算法和容器。
[capture list] (parameter list) -> return type { function body }
1.capture list: 捕获列表,
[=],意味着外部作用域以by value的方式传递给lambda。因此,当这个lambda被定义时,你可以读取所有可读的数据,但是不能改动他们。
[&],意味着外部作用域以by reference方式传递给lambda。因此,当所有数据的涂写动作都合法。
mutable :在 参数列表 和执行代码直接声明,可以认为所有都是以by reference传递
2.parameter list: 参数列表
3.return type: 返回类型
4.function body: 执行代码
实例如下:
#include <iostream>
#include <string>
#include <functional>
using namespace std;
std::function<int(int, int)> returnLambda()
{
return [](int x, int y) {return x * y; };
}
int main()
{
/*auto l = [] {cout << "hello lambda" << endl; }; //无参lambda
l();*/
/*auto l = [](const string& s) {cout << s << endl; };
l("hello lambda");*/ //有参lambda
int x = 0;
int m = 1;
int y = 2;
int n = 3;
auto qqq = [x, &y, &m, n]()
{ //x++; 无法编译过
y--;
cout << x << y << m << n << endl;
};//有捕获列表lambda
qqq();
cout << "x=" << x << endl;
cout << "y=" << y << endl;
//auto lf = returnLambda();
//cout << lf(6, 7) << endl;
}