Frage

Mit C ++ 0x, wie kann ich eine Variable erfassen, wenn ich eine Lambda in einem Lambda haben? Zum Beispiel:

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
            });
    });
War es hilfreich?

Lösung

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

Nicht besonders sauber, aber es funktioniert.

Andere Tipps

Das Beste, was ich tun konnte, ist dies:

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

Interessantes Problem! Ich werde darüber schlafen und sehen, ob ich etwas besser herausfinden kann.

In der inneren Lambda sollten Sie haben (vorausgesetzt, Sie die Variable durch Verweis übergeben möchten):

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

  int a =v;
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top