代码之家  ›  专栏  ›  技术社区  ›  DanDan

C++ 0x中的闭包和嵌套lambda

  •  14
  • DanDan  · 技术社区  · 15 年前

    使用C++ 0x,当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
                });
        });
    
    3 回复  |  直到 15 年前
        1
  •  8
  •   Timothy003    14 年前
    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;
                    }
                );
            }
        );
    

        2
  •  1
  •   Blindy    15 年前

    我能想到的最好办法是:

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

    有趣的问题!我再考虑一下,看看能不能想出更好的办法。

        3
  •  0
  •   Stephan    12 年前

    在内部lambda中,您应该有(假设您希望通过引用传递变量):

    [&v](int num)->void{
    
      int a =v;
    }