我什么时候应该使用 unordered_map 而不是 std::map

发布于 2024-11-10 07:14:23 字数 96 浏览 4 评论 0原文

我想知道在哪种情况下应该使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

冰魂雪魄 2024-11-17 07:14:23

map

  1. 通常使用红黑树实现。
  2. 元素已排序。
  3. 内存使用量相对较小(哈希表不需要额外的内存)。
  4. 相对快速的查找:O(log N)。

unordered_map

  1. 通常使用哈希表实现。
  2. 元素未排序。
  3. 需要额外的内存来保存哈希表。
  4. 快速查找 O(1),但恒定时间取决于 哈希函数,这可能相对较慢。另请记住,您可能会遇到生日问题

map

  1. Usually implemented using red-black tree.
  2. Elements are sorted.
  3. Relatively small memory usage (doesn't need additional memory for the hash-table).
  4. Relatively fast lookup: O(log N).

unordered_map

  1. Usually implemented using hash-table.
  2. Elements are not sorted.
  3. Requires additional memory to keep the hash-table.
  4. Fast lookup O(1), but constant time depends on the hash-function which could be relatively slow. Also keep in mind that you could meet with the Birthday problem.
不如归去 2024-11-17 07:14:23

比较哈希表 (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.

一绘本一梦想 2024-11-17 07:14:23

map 允许以排序方式迭代元素,但 unordered_map 不允许。
因此,当您需要按排序顺序迭代映射中的项目时,请使用 std::map

map allows to iterate over the elements in a sorted way, but unordered_map does not.
So use the std::map when you need to iterate across items in the map in sorted order.

箹锭⒈辈孓 2024-11-17 07:14:23

您选择其中之一的原因是性能。否则,他们只会创建 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. Use std::unordered_map other times.

See the SGI STL Complexity Specifications rationale.

牵你的手,一向走下去 2024-11-17 07:14:23

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文