c++ - += 一对运算符和 make_pair 与模板

标签 c++ templates stl

我在阅读图书馆的代码库时遇到了以下问题。

errorMap,在下面的代码中使用定义为:

map <const string, pair<int, double>> errorMap;

代码的相关部分是:

errorMap["substitutions"] += make_pair<int,double>(targetLength, substitutions);
errorMap["insertions"] += make_pair<int,double>(targetLength, insertions);
errorMap["deletions"] += make_pair<int,double>(targetLength, deletions);

以上部分是抛this编译错误。当通过它自己的构建系统运行库时,代码似乎正在编译。有人可以阐明这里到底发生了什么吗?

PS:我已经查看了 cppreference 和其他网站上的配对文档,它们都没有为配对指定 += 运算符。这是我第一次遇到带有模板参数的 make_pair,我也找不到更多信息。

最佳答案

这与配对无关,与 map 有关。 operator [] 用于在 map 中插入或更新元素。

例如在 std::map<char, int> myMap{{'a', 27}, {'b', 3}, {'c', 1}}; ,我可以执行以下操作(如上面链接的页面所示):

myMap['a'] = 6; //to change the value associated to 'a'
myMap['d'] = 8; //to insert a new value

我还可以执行以下操作:

myMap['b'] += 9; //Now the value associated to b is 3 + 9 = 12

在问题中发布的 3 行代码中,正在更新与括号内的字符串关联的值。

operator+=对于与模板的配对,可能已经过载。 (查看此 question 的答案)这可能就是为什么您会收到这些错误而不是以下错误(将字符替换为字符串):

error: no match for ‘operator+=’ (operand types are ‘std::map<char, std::pair<int, double> >::mapped_type {aka std::pair<int, double>}’ and ‘std::pair<int, double>’)

由于相同的操作不会重现相同的错误,问题来自更深层次的实现,而您没有提供上下文。它们可能与右值和左值有关:

cannot convert ‘targetLength’ (type ‘int’) to type ‘int&&’

您[可能][1] 想看看那些 answers为此。

[1]:可能是因为我不确定自己在说什么。我想发表评论,但没有足够的代表,所以我尽力回答。

关于c++ - += 一对运算符和 make_pair 与模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43839897/

相关文章:

c++ - 部分专用模板的声明不完整

javascript - Backbone : Using views inside _. 模板

c++ - 处理 utf-8 字符串 gtk

c++ - struct hack - 大小为零的数组

c++ - 作为映射键的对象在 cpp 中变为 const

c++ - C 和 C++ 中的嵌套结构

使用STL map的运算符[]时android ndk崩溃

c++ - 第一次计算后的错误值

javascript - Knockout 没有使用我的数据渲染模板

c++ - 如何在包含指向元素的指针的集合中找到元素?