unordered_multimap元素输出顺序很奇怪
我们知道unordered_multimap没有排序元素。(可能...我是菜鸟:) 因此,unordered_multimap中元素的顺序是按输入顺序进行的。 现在,我输入了5个最简单的字母,即A,B,C,D,e。 首先,请猜测元素输出哪个顺序? 输入顺序ABCDE是相同的吗? 输入顺序EDCBA的相反吗? 这是荒谬的edc a b !!! 我测试了许多输入。 Alaways反向顺序和最后两个元素是顺序。 我听不懂。
int main()
{
unordered_multimap<char, int> window;
window.insert(make_pair('A',1));
window.insert(make_pair('B',1));
window.insert(make_pair('C',1));
window.insert(make_pair('D',1));
window.insert(make_pair('E',1));
for (unordered_multimap<char, int>::iterator it = window.begin(); it != window.end(); it++)
cout<<it->first<<endl;
return 0;
}
We know that unordered_multimap does not sort elements.(Probably...I'm Noob:)
So the order of elements in unordered_multimap is by order of input.
Now I inputed 5 simplest letter that A,B,C,D,E.
First please guess elements output in which order?
Is same at input order A B C D E?
Is the reverse of input order E D C B A?
It is ridiculous E D C A B!!!
I tested many input. Alaways reverse order and the last two elements is order.
I can't understand it.
int main()
{
unordered_multimap<char, int> window;
window.insert(make_pair('A',1));
window.insert(make_pair('B',1));
window.insert(make_pair('C',1));
window.insert(make_pair('D',1));
window.insert(make_pair('E',1));
for (unordered_multimap<char, int>::iterator it = window.begin(); it != window.end(); it++)
cout<<it->first<<endl;
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
!名称为无序;根本没有有用的,可预测的排序。在引擎盖下,它们以
不要依靠 在
unordered_map
中订购;如果您需要订购,则必须自己强加它,或使用类似于Java的linkedHashmap
的第三方哈希表结构,该结构将链接列表结构与哈希表结合在一起以获取插入订购的迭代。NOPE! The name is unordered; there is no useful, predictable ordering involved at all. Under the hood, they're implemented as hash tables, and the nature of hash tables means that the iteration ordering depends on the hash values of the keys (which are frequently unrelated to their sort order), the size of the underlying table (which resizes as more keys are inserted) and the order in which keys were inserted or deleted. The hashing rules for most built-in types are implementation-defined, so they'll change from compiler to compiler.
Don't rely on any ordering in
unordered_map
; if you need ordering, you'll have to impose it yourself, or use third-party hash table structures similar to Java'sLinkedHashMap
that integrate a linked list structure with a hash table to get insertion-ordered iteration.请参阅 unordered_multimimap
顺便说一句,因为 unordered_multimap支持等效键,因此不能保证同一密钥的存储顺序被订购。
refer to unordered_multimap
By the way, because unordered_multimap supports equivalent keys, the storage order of the same key is not guaranteed to be ordered.