L-value在使用std::map时指定const对象
l-value specifies const object while using std::map
我正在尝试使用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 filesmicrosoft visual studio 10.0vcincludeutility(260): error C2166: l-value specifies const object
1> c:program filesmicrosoft visual studio 10.0vcincludeutility(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 testsmaptestmaptestmaptest.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> ]
我不明白为什么调用operator =,虽然我通过引用在lambda-function中传递val。你能解释一下我做错了什么吗?
您不能将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;
}
}
下面是一个的实例
相关文章:
- 被解释为低级别const的const对象的地址
- 在 C++ 中声明 const 对象需要用户定义的默认构造函数.如果我有一个可变成员变量,为什么不呢?
- Google Or-Tools Glop:如何创建指向 const 对象的指针数组?
- 我们可以有一个 setter 成员函数作为从 const 对象引用的 const 吗?
- "this"指向的对象是否与 const 对象相同?
- 从 const 对象访问非 const 方法
- 将非 const 对象用于 const 参数
- 如何键入用于const对象的自定义io操纵器
- 哪个 const 与哪个引用将更改参数并创建一个 const 对象?
- 无法在返回中转换 const 对象
- 接受对 const 对象的引用但没有 r 值的函数
- 当我调用 main 中使用 const 对象的 const 函数时,不断出现错误
- 在 const 对象上调用非 const 函数
- 正确的方法通过巨大的const对象的向量
- 如何重载 const 对象的 [],以便值赋值不会导致编译错误
- 相互引用的 Const 对象
- 析构函数是否可以在 const 对象上调用非 const 函数
- decltype 不会推断 const 对象的 const 成员
- 防止const函数被调用非const对象
- constexpr引用非const对象