unordered_multimap-迭代find()的结果会产生具有不同值的元素
unordered_multimap - iterating the result of find() yields elements with different value
C++中的多映射似乎很奇怪,我想知道为什么
#include <iostream>
#include <unordered_map>
using namespace std;
typedef unordered_multimap<char,int> MyMap;
int main(int argc, char **argv)
{
MyMap map;
map.insert(MyMap::value_type('a', 1));
map.insert(MyMap::value_type('b', 2));
map.insert(MyMap::value_type('c', 3));
map.insert(MyMap::value_type('d', 4));
map.insert(MyMap::value_type('a', 7));
map.insert(MyMap::value_type('b', 18));
for(auto it = map.begin(); it != map.end(); it++) {
cout << it->first << 't';
cout << it->second << endl;
}
cout << "all values to a" << endl;
for(auto it = map.find('a'); it != map.end(); it++) {
cout << it->first << 't' << it->second << endl;
}
}
这是输出:
c 3
d 4
a 1
a 7
b 2
b 18
all values to a
a 1
a 7
b 2
b 18
当我明确要求"a"时,为什么输出中仍然包含以b为键的内容?这是编译器错误还是stl错误?
find
在实现时,为与多映射中的键匹配的第一个元素返回迭代器(与任何其他映射一样)。您可能正在寻找equal_range
:
// Finds a range containing all elements whose key is k.
// pair<iterator, iterator> equal_range(const key_type& k)
auto its = map.equal_range('a');
for (auto it = its.first; it != its.second; ++it) {
cout << it->first << 't' << it->second << endl;
}
这不是一个bug,而是设计出来的。find
向其中一个匹配元素返回迭代器,仅此而已。您将使用您的构造迭代到映射的末尾。
你需要使用multimap::equal_range
来做你想要做的事情。
www.cplusplus.com中有一个例子,关于如何使用equal_range方法来获取具有相同键的所有元素。
// unordered_multimap::equal_range
#include <iostream>
#include <string>
#include <unordered_map>
#include <algorithm>
typedef std::unordered_multimap<std::string,std::string> stringmap;
int main ()
{
stringmap myumm = {
{"orange","FL"},
{"strawberry","LA"},
{"strawberry","OK"},
{"pumpkin","NH"}
};
std::cout << "Entries with strawberry:";
auto range = myumm.equal_range("strawberry");
for_each (
range.first,
range.second,
[](stringmap::value_type& x){std::cout << " " << x.second;}
);
return 0;
}
请参考链接:http://www.cplusplus.com/reference/unordered_map/unordered_multimap/equal_range/
似乎您将迭代器放入对的完整"列表"中,从第一对开始,以"a"作为键。因此,当你迭代到最后时,自然你也会得到"a"之外的一切。如果你寻找"c",你可能会在整个"列表"中重复你在那里做的事情。如果你想要所有的a,也许你应该迭代到"it!=map.end()&it->first=='a'"。
相关文章:
- C++:使用类在向量中搜索特定元素时,我得到了错误的结果
- AVX2 整数乘以有符号 8 位元素,产生有符号 16 位结果?
- 如何通过查找迭代器结果分配给一组对的元素
- 使用指针访问数组元素时出现意外结果
- 我写了这个简单的代码,应该计算一系列数组元素的最高数量,但结果很奇怪
- 打印整数指针元素时的结果不同
- 使用算法中的插入函数将元素插入空容器中,未给出预期的结果
- 从函数的返回值将元素C++存储到 std::vector 中时出现意外结果
- 第一个字符串元素的地址产生意外结果
- 求和数组的每个元素的函数的结果
- 将多态函数应用于每个元组元素的结果类型
- 试图将字符串的两个元素组合在一起会得到错误的结果(c++)
- 为什么我的程序是,数组中任意两个元素之间的最小差异,给出相反的结果
- 如何将函数静态应用于非类型模板包的各个元素并对结果求和
- 如何进行每个元素的比较,并根据结果进行不同的操作
- 在条件与外部获取数组元素的结果不同
- unordered_multimap-迭代find()的结果会产生具有不同值的元素
- 在哪里存储Visitor模式中访问的每个元素的计算结果
- 是否有可能判断哪个数组元素比较结果为真?
- 如何使用本函数对两个字符数组进行元素相乘,并将相乘结果求和为int