轉載請註明,來自:http://blog.csdn.net/skymanwu
#include <iostream>
#include <vector>
#include <functional>
using namespace std;
vector<function<int(int)>> v;
// lambda使用function封裝
function<int(int)> f1(int k)
{
return function<int(int)>([=](int x) -> int
{
if(x > k)
return 1;
else if(x == k)
return 0;
else
return -1;
});
}
// 要使用lambda表達式作爲參數,需用函數模版
template<typename Lambda>
void f2(Lambda l, int i)
{
cout<< l(i) <<endl;
}
int main()
{
auto g = f1(10);
v.push_back(g);
for(vector<function<int(int)>>::iterator iter = v.begin(); iter != v.end(); ++iter)
{
cout << (*iter)(9) << endl;
cout << (*iter)(10) << endl;
cout << (*iter)(11) << endl;
}
int k = 10;
auto lambda = [=](int x) -> int
{
if(x > k)
return 1;
else if(x == k)
return 0;
else
return -1;
};
k = 6;
f2(lambda, 8);
return 0;
}
輸出結果:
-1
0
1
-1
lambda 引入符:
1. [] //不捕獲任何外部變量
2. [=] //以值的形式捕獲所有外部變量
3. [&] //以引用形式捕獲所有外部變量
4. [x, &y] //x以傳值形式捕獲,y以引用形式捕獲
5. [=, &z] //z以引用形式捕獲,其餘變量以傳值形式捕獲
6. [&, x] //x以值的形式捕獲,其餘變量以引用形式捕獲
例如上面的代碼中,將“auto lambda = [=](int x) -> int”中的“=”改爲"&",則k就是引用捕獲,運行返回值則爲1。