在 std::map 长字符串中查找编译错误

Compilation error in find in a std::map of string, long

我正在 Visual Studio 2013 VC++ 中工作。 我有一个std::map如下,

std::map<std::string, unsigned int> myMap;

作为 class 的静态成员。

我通过这样做将值填充到其中,

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())

有人可以帮我解决这个问题吗?

谢谢

wouldn't be getting this error 如果你的声明实际上是:

std::map<std::string, unsigned int> myMap

你会 get this exact error 但是如果你的定义是偶然的:

std::map<std::string, long> myMap

Herb Sutter 在其著名的 Almost Always Auto 中设定了准则:

Remember that preferring auto variables is motivated primarily by correctness, performance, maintainability, and robustness—and only lastly about typing convenience.

正如 Herb Sutter 所建议的那样 auto(和 make_pair)不仅可以使您的代码正确,而且可以使其更健壮,也就是说它将支持 myMap 独立于您使用了上述哪些声明的声明:

const string key = "value"s;
const auto it = arg.find(key);

if(it == arg.end()) {
    arg.insert(make_pair(key, 1));
} else {
    int prev_value = it->second;
    prev_value++;
    arg.insert(make_pair(key, prev_value));
}

Live Example

编辑:

that map::insert:

Inserts element(s) into the container, if the container doesn't already contain an element with an equivalent key

意味着您的整个 else 块不会执行任何操作,因为它仅在 map 已经包含具有等效键的元素时才会触发。大概您打算使用 map::insert_or_assign 或类似的,在这种情况下,您的整个代码应该简单地替换为:

++myMap["value"s]

EDIT2:

请注意,上面的代码之所以有效,是因为在 C++ 中,下标运算符的优先级高于前缀递增运算符。但是 myMap["value"s]++ 将不起作用,因为后缀增量的优先级高于下标运算符。有关运算符优先级的更多信息,请参阅 C++ operator precedence chart

在这种情况下,这种排序是一件好事,因为它迫使您做出更好的编码决策。具体来说,在 C++ 中,出于优化原因,最佳实践是使用 prefix 增量运算符而不是 postfix 增量运算符(尽管在大多数情况下现代编译器会清除这对你来说仍然是最佳实践。)