Closure和嵌套的lambdas在C ++ 0x [英] Closure and nested lambdas in C++0x

查看:125
本文介绍了Closure和嵌套的lambdas在C ++ 0x的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用C ++ 0x,当我在lambda中有一个lambda时,如何捕获一个变量?例如:

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.

这篇关于Closure和嵌套的lambdas在C ++ 0x的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆