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

标签 c++ lambda c++11 visual-c++-2010

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

最佳答案

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

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

关于c++ - C++0x 中的闭包和嵌套 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2891690/

相关文章:

c++ - 错误: Cannot synthesize a Constructor for A

c++ - std::thread 使用带有 ref arg 的 lambda 编译失败

c++ - [[nodiscard]] 在 std::function 返回类型定义中?

c++ - 优化C++位图处理算法

c++ - 包含在 main.cpp 中的 header 有效,但在类中抛出错误

java - 过滤后无法返回子类对象的Stream

c# - 表达式 lambda 和语句 lambda 的区别

c++ - 右值引用、复制和移动

c++11 - std::pair 的 switch 语句?

c++ - 在 C++ 中将 std::wstring 转换为 const *char