Using C++0x, how do I capture a variable when I have a lambda within a lambda? For example:
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;
}
);
}
);
Not especially clean, but it does work.
The best I could come up with is this:
std::vector<int> c1;
int v = 10;
std::for_each(
c1.begin(),
c1.end(),
[v](int num)
{
std::vector<int> c2;
int vv=v;
std::for_each(
c2.begin(),
c2.end(),
[&](int num) // <-- can replace & with vv
{
int a=vv;
});
});
Interesting problem! I'll sleep on it and see if i can figure something better out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With