14

使用 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
            });
    });
4

3 回答 3

8
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;
                }
            );
        }
    );

不是特别干净,但确实有效。

于 2010-05-23T12:35:43.097 回答
1

我能想到的最好的是:

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;
            });
    });

有趣的问题!我会睡在上面,看看我能不能想出更好的办法。

于 2010-05-23T12:32:45.940 回答
0

在内部 lambda 你应该有(假设你想通过引用传递变量):

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

  int a =v;
}
于 2011-04-12T09:22:50.180 回答