【发布时间】:2017-01-07 05:19:09
【问题描述】:
我正在使用 VC++ 开发 Visual Studio 2013。 我有一个 std::map 如下,
std::map<std::string, unsigned int> myMap;
作为类的静态成员。
我通过这样做将值填充到其中,
string key = "value";
std::map<std::string, unsigned int>::iterator it = myMap.find(key);
if(it == myMap.end())
myMap.insert(std::pair<std::string, unsigned int> (key, 1));
else
{
int prev_value = it->second;
prev_value++;
myMap.insert(std::pair<std::string, unsigned int> (key, prev_value));
}
这不编译,我得到这个编译错误,
1 IntelliSense: no suitable user-defined conversion from "std::_Tree_iterator<std::_Tree_val<std::_Tree_simple_types<std::pair<const std::string, long>>>>" to "std::_Tree_iterator<std::_Tree_val<std::_Tree_simple_types<std::pair<const std::string, unsigned int>>>>" exists c:\filename.cpp 15
15 是这一行,
std::map<std::string, unsigned int>::iterator it = myMap.find(key);
还有这个错误,
2 IntelliSense: no operator "==" matches these operands
operand types are: std::_Tree_iterator<std::_Tree_val<std::_Tree_simple_types<std::pair<const std::string, unsigned int>>>> == std::_Tree_iterator<std::_Tree_val<std::_Tree_simple_types<std::pair<const std::string, long>>>> c:\filename.cpp 17
第 17 行是这样的,
if(it == myMap.end())
有人可以帮我解决这个问题吗?
谢谢
【问题讨论】:
-
错误消息表明
myMap实际上是std::map<std::string, long>类型,而不是您声称的std::map<std::string, unsigned int>。为了避免猜测迭代器的正确类型,只需使用auto,如auto it = myMap.find(key); -
还要注意
myMap.insert不会替换已存在键的值。整个段落可以替换为++myMap["value"];- 这对新密钥和现有密钥都是正确的。 -
@IgorTandetnik Arg,你打败了我。像一个小时。在发布我的答案之前,我应该已经加载了 cmets。您已经用 2 个简单的 cmets 总结了我的全部答案 :(
标签: c++ visual-studio compiler-errors stdmap