C ++ Lambdas:捕获列表与参数列表 [英] C++ Lambdas: capture list vs. parameter list
问题描述
根据C ++ 11标准,lambda表达式可以通过捕获列表,参数列表或同时使用这两者在封闭范围内使用变量。
According to the C++11 standard, lambda expressions may use variables in the enclosing scope, by means of the capture list, the parameter list or both.
所以,让我们看一下相同代码的两个版本。
So, let's look to two versions of the same code.
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;
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;
输出为:
With capture : Factorial of 4 = 24
With parameter: Factorial of 4 = 24
由于我们可以将参数传递给参数列表中的lambda(就像使用任何C ++函数一样),为什么我们需要捕获列表?
Since we can pass parameters to lambdas in the parameter list (just as with any C++ function), why do we need the capture list?
可以有人告诉我参数列表不起作用而只有捕获列表起作用的情况吗?
Can someone show me cases where parameter list doesn't work and only capture list does?
推荐答案
例如,使用stl算法:
For example using stl algorithms:
std::vector<int> items;
int factor;
auto foundItem = std::find_if(items.begin(), items.end(),
[&factor](int const& a)
{
return a * factor == 100;
});
在这种情况下,您会在容器中为每个项目调用lambda,如果返回则返回值乘以捕获的因子就是100。
代码没有多大意义,只是向您展示捕获和参数列表很重要的示例。
In this case you're called in the lambda for every item in the container and you return if the value multiplied by a captured factor is 100. The code doesn't make much sense, it's just to show you an example where capture and parameter lists matter.
这篇关于C ++ Lambdas:捕获列表与参数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!