使用 C++0x,当我在 lambda 中有一个 lambda 时,如何捕获一个变量?例如:
std::vector<int> c1;
int v = 10; <--- I want to capture this variable
std::for_each(
c1.begin(),
c1.end(),
[v](int num) <--- This is fine...
{
std::vector<int> c2;
std::for_each(
c2.begin(),
c2.end(),
[v](int num) <--- error on this line, how do I recapture v?
{
// Do something
});
});
最佳答案
std::for_each(
c1.begin(),
c1.end(),
[&](int num)
{
std::vector<int> c2;
int& v_ = v;
std::for_each(
c2.begin(),
c2.end(),
[&](int num)
{
v_ = num;
}
);
}
);
不是特别干净,但确实有效。
关于c++ - C++0x 中的闭包和嵌套 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2891690/