【问题标题】:l-value specifies const object while using std::mapl-value 在使用 std::map 时指定 const 对象
【发布时间】:2013-04-26 08:06:56
【问题描述】:

我正在尝试使用 std::map ,如下例所示:

#include <map>
#include <algorithm>

int wmain(int argc, wchar_t* argv[])
{
    typedef std::map<int, std::wstring> TestMap;
    TestMap testMap;
    testMap.insert(std::make_pair(0, L"null"));
    testMap.insert(std::make_pair(1, L"one"));
    testMap.erase(std::remove_if(testMap.begin(), testMap.end(), [&](const TestMap::value_type& val){ return !val.second.compare(L"one"); }), testMap.end());
    return 0;
}

我的编译器(VS2010)给了我以下信息:

>c:\program files\microsoft visual studio 10.0\vc\include\utility(260): error C2166: l-value specifies const object

1>          c:\program files\microsoft visual studio 10.0\vc\include\utility(259) : while compiling class template member function 'std::pair<_Ty1,_Ty2> &std::pair<_Ty1,_Ty2>::operator =(std::pair<_Ty1,_Ty2> &&)'
1>          with
1>          [
1>              _Ty1=const int,
1>              _Ty2=std::wstring
1>          ]
1>          e:\my examples\с++\language tests\maptest\maptest\maptest.cpp(8) : see reference to class template instantiation 'std::pair<_Ty1,_Ty2>' being compiled
1>          with
1>          [
1>              _Ty1=const int,
1>              _Ty2=std::wstring
1>          ]

虽然我通过引用在 lambda 函数中传递了 val,但我不明白为什么调用 opertor =。 你能解释一下我做错了什么吗?

【问题讨论】:

  • 错误信息在第 8 行,lambda 在第 10 行。看起来配对分配发生在 insert(),并且与 lambda 无关。
  • map, lambda, remove_if 的可能重复项

标签: c++ visual-c++ c++11 stl


【解决方案1】:

您不能将std::remove_if 与关联容器一起使用,因为该算法通过用后续元素覆盖已删除元素来工作:这里的问题是地图的键是常量,以防止您(或std::remove_if 算法)不会弄乱容器的内部排序。

要有条件地从地图中删除元素,不如这样做:

for (auto iter = testMap.begin(); iter != testMap.end();)
{
    if (!iter->second.compare(L"one")) // Or whatever your condition is...
    {
        testMap.erase(iter++);
    }
    else
    {
        ++iter;
    }
}

这是live example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 2017-04-05
    • 2017-10-31
    相关资源
    最近更新 更多