문제

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.

In the inner lambda you should have(assuming you want to pass the variable by reference):

[&v](int num)->void{

  int a =v;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top