[英]When should I use unordered_map and not std::map
I'm wondering in which case I should use unordered_map instead of std::map.我想知道在哪种情况下我应该使用 unordered_map 而不是 std::map。
I have to use unorderd_map each time I don't pay attention of order of element in the map?每次我不注意 map 中的元素顺序时,我都必须使用 unorderd_map?
map
unordered_map
Compare hash table ( undorded_map
) vs. binary tree ( map
), remember your CS classes and adjust accordingly.比较 hash 表(
undorded_map
)与二叉树( map
),记住你的 CS 类并进行相应调整。
The hash map usually has O(1) on lookups, the map has O(logN). hash map 的查找时间通常为 O(1),map 的查找时间为 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 保持元素的顺序,这有时也很有用。
map
allows to iterate over the elements in a sorted way, but unordered_map
does not. map
允许以排序方式遍历元素,但unordered_map
不允许。
So use the std::map
when you need to iterate across items in the map in sorted order.因此,当您需要按排序顺序遍历 map 中的项目时,请使用
std::map
。
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:)否则他们只会创建
std::map
,因为它为你做的更多:)
Use std::map
when you need elements to automatically be sorted.当您需要对元素进行自动排序时,请使用
std::map
。 Use std::unordered_map
other times.其他时间使用
std::unordered_map
。
See the SGI STL Complexity Specifications rationale .请参阅SGI STL 复杂性规范基本原理。
unordered_map
is O(1) but quite high constant overhead for lookup, insertion, and deletion. unordered_map
是 O(1),但查找、插入和删除的持续开销相当高。 map
is O(log(n)), so pick the complexity that best suits your needs. map
为 O(log(n)),因此请选择最适合您需求的复杂度。 In addition, not all keys can be placed into both kinds of map.此外,并非所有的键都可以放入这两种 map 中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.