根据C++ 11标准,lambda表达式可以通过捕获列表,参数列表或两者使用封闭范围中的变量.
那么,让我们看看相同代码的两个版本.
1)捕获
int x = 4;
cout << "With capture : Factorial of " << x << " = " << [x]() // <= Capture
{
int r = 1;
for (int i = x; i > 1; i--) r = r * i;
return r;
}() << endl;
Run Code Online (Sandbox Code Playgroud)
2)带参数
int x = 4;
cout << "With parameter: Factorial of " << x << " = " << [](int x) // <= Parameter
{
int r = 1;
for (int i = x; i > 1; i--) r = r * i;
return r;
}(x) << endl;
Run Code Online (Sandbox Code Playgroud)
输出是:
With capture : Factorial of 4 = 24
With parameter: Factorial of 4 = 24
Run Code Online (Sandbox Code Playgroud)
由于我们可以在参数列表中将参数传递给lambdas(就像任何C++函数一样),为什么我们需要捕获列表?
有人可以告诉我参数列表不起作用的情况,只有捕获列表吗?
dau*_*ama 23
例如,使用stl算法:
std::vector<int> items;
int factor;
auto foundItem = std::find_if(items.begin(), items.end(),
[&factor](int const& a)
{
return a * factor == 100;
});
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您在lambda中为容器中的每个项调用,如果值乘以捕获的因子为100,则返回.代码没有多大意义,它只是向您展示捕获和参数的示例列出事项.
关键是,通过捕获,您可以在类似函数的对象中保持一个状态(就像一个带有operator()的手写类).@dau_sama给出了一个很好的答案.这是另一个例子:
#include <iostream>
using namespace std;
int main() {
const auto addSome = [](double some){
return [some](double val){ return some+val; } ;
};
const auto addFive = addSome(5);
std::cout << addFive(2) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)