c++ - 为什么 std::map 在按值传递给 lambda 时表现异常?

标签 c++ c++11

我使用 c++ 0x 已经有一段时间了,并且非常喜欢新的 lamba 函数工具。我已经习惯于在我的 lambda 声明中指定 [=] 来表示我想按值将外部范围的变量传递到我的 lambda 中。

但是,今天我遇到了一个非常奇怪的 lambda 问题。我注意到在 for_each 期间按值将外部范围的映射传递到 lamba 工作很奇怪。这是显示问题的示例:

void LambdaOddnessOne ()
{
    map<int, wstring> str2int;
    str2int.insert(make_pair(1, L"one"));
    str2int.insert(make_pair(2, L"two"));

    vector<int> numbers;
    numbers.push_back(1);
    numbers.push_back(2);

    for_each ( numbers.begin(), numbers.end(), [=]( int num ) 
    {
        //Calling find() compiles and runs just fine
        if (str2int.find(num) != str2int.end())
        {
            //This won't compile... although it will outside the lambda
            str2int[num] = L"three";

            //Neither will this saying "4 overloads have no legal conversion for 'this' pointer"
            str2int.insert(make_pair(3, L"three"));
        }
    });

}

许多 map 的方法可以从 lamba 内部调用(例如 find),但是许多其他方法在 lamba 外部编译得很好时会导致编译错误。

例如,尝试使用 [ 运算符会导致:

error C2678: binary '[' : no operator found which takes a left-hand operand of type 'const std::map<_Kty,_Ty>' (or there is no acceptable conversion)

尝试使用 .insert 函数导致:

error C2663: 'std::_Tree<_Traits>::insert' : 4 overloads have no legal conversion for 'this' pointer

有人理解这种不一致的行为吗?这只是 MS 编译器的问题吗?我没有尝试过任何其他的。

最佳答案

关于c++ - 为什么 std::map 在按值传递给 lambda 时表现异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6280974/

相关文章:

c++ - 无效的协变返回类型

c++ - C++:循环优化和循环展开(循环或不循环)

c++ - 我将如何在 C++20 中传递范围而不是迭代器对?

c++ - 判断 C++11 unordered_set 中是否发生碰撞

c++ - cpp文件中的C++变量能否定义为特殊符号β

c++ - 将 std::vector<std::unique_ptr<T>> 分配给另一个 std::vector<std::unique_ptr<T>>

c++ - 重载运算符 += C++ 时出错

C++ - 如何以平台无关、线程安全的方式将文件的上次修改日期和时间格式化为用户首选的日期/时间区域设置格式

c++ - 无法将 'std::ostream {aka std::basic_ostream<char>}' 左值绑定(bind)到 'std::basic_ostream<char>&&'

c++ - 这个使用 using 的可变参数模板如何工作?