根据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; …
Run Code Online (Sandbox Code Playgroud)