我什么时候应该使用 unordered_map 而不是 std::map
我想知道在哪种情况下应该使用 unordered_map 而不是 std::map。
每次我不注意地图中元素的顺序时,我都必须使用 unorderd_map 吗?
I'm wondering in which case I should use unordered_map instead of std::map.
I have to use unorderd_map each time I don't pay attention of order of element in the map ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
map
unordered_map
map
unordered_map
比较哈希表 (
undorded_map
) 与二叉树 (map
),记住您的 CS 类并进行相应调整。哈希映射的查找时间复杂度通常为 O(1),映射的查找时间复杂度为 O(logN)。如果您需要多次快速查找,这可能是一个真正的区别。
地图保持元素的顺序,这有时也很有用。
Compare hash table (
undorded_map
) vs. binary tree (map
), remember your CS classes and adjust accordingly.The hash map usually has O(1) on lookups, the map has O(logN). It can be a real difference if you need many fast lookups.
The map keeps the order of the elements, which is also useful sometimes.
map
允许以排序方式迭代元素,但unordered_map
不允许。因此,当您需要按排序顺序迭代映射中的项目时,请使用
std::map
。map
allows to iterate over the elements in a sorted way, butunordered_map
does not.So use the
std::map
when you need to iterate across items in the map in sorted order.您选择其中之一的原因是性能。否则,他们只会创建
std::map
,因为它可以为您做更多事情:)当您需要自动对元素进行排序时,请使用
std::map
。其他时候使用 std::unordered_map 。请参阅SGI STL 复杂性规范基本原理。
The reason you'd choose one over the other is performance. Otherwise they'd only have created
std::map
, since it does more for you :)Use
std::map
when you need elements to automatically be sorted. Usestd::unordered_map
other times.See the SGI STL Complexity Specifications rationale.
unordered_map
的复杂度为 O(1),但查找、插入和删除的恒定开销相当高。map
的复杂度为 O(log(n)),因此请选择最适合您需求的复杂度。另外,并不是所有的键都可以放入这两种地图中。unordered_map
is O(1) but quite high constant overhead for lookup, insertion, and deletion.map
is O(log(n)), so pick the complexity that best suits your needs. In addition, not all keys can be placed into both kinds of map.