简体   繁体   English

使用整数键和向量的映射之间的差异

[英]Difference Between Map with Integer Key and Vector

Is vector the specialized form of unordered_map with integer key? 向量是带有整数键的unordered_map的特殊形式吗? It seems so because a vector has integer keys, too. 看起来是这样,因为矢量也有整数键。

If not, what are the differences? 如果没有,有什么区别?

Vector is a container around an array. Vector是一个数组周围的容器。

An unordered map is a container around a binary tree. 无序映射是二叉树周围的容器。

That means they have different performance characteristics. 这意味着它们具有不同的性能特征。 Some examples: 一些例子:

  • Accessing an element by index is a constant-time operation in a vector/array, but a logarithmic time operation in a binary tree. 通过索引访问元素是向量/数组中的常量时间操作,但是是二叉树中的对数时间操作。 Both are cheap, but on a vector it's even faster. 两者都很便宜,但在矢量上它甚至更快。
  • Increasing the capacity of a vector is expensive (linear time), but cheap for a binary tree (logarithmic time). 增加向量的容量是昂贵的(线性时间),但对于二叉树来说是便宜的(对数时间)。

The main difference is in how the data is stored. 主要区别在于数据的存储方式。

A vector stores the data in an internal array that it resizes and you add more elements. vector将数据存储在调整大小的内部数组中,并添加更多元素。 An unordered_map uses a hash table internally. unordered_map在内部使用哈希表。

Practically, a vector gives you amortized constant time insertions at the back (it needs to resize and copy/move everything once in a while), constant time access by index, and up to linear time insertion and deletion (all the subsequent elements have to be shifted). 实际上, vector为您提供在后面分配的常量时间插入(它需要一次调整大小并复制/移动所有内容),通过索引进行常量时间访问,以及最多线性时间插入和删除(所有后续元素必须转移)。 Also, since a vector is contiguous, you can pass it into functions expecting a c-style array. 此外,由于vector是连续的,您可以将其传递给期望c样式数组的函数。

unordered_map gives you amortized constant time lookup by key (because hashing is not perfect, and collisions force the lookup to traverse through internal linked lists), amortized constant time inserts and deletes. unordered_map为您提供按密钥分摊的常量时间(因为散列不完美,并且冲突会强制查找遍历内部链接列表),分摊的常量时间插入和删除。

See: http://en.cppreference.com/w/cpp/container/unordered_map and: http://en.cppreference.com/w/cpp/container/vector 请参阅: http//en.cppreference.com/w/cpp/container/unordered_map和: http//en.cppreference.com/w/cpp/container/vector

Nope, indexes in a vector are continuous, in a map they don't have to be. 不, vector中的索引是连续的,在map它们不一定是。

Also, values in a vector are guaranteed to be in continuous memory, not in a map . 此外, vector中的值保证在连续内存中,而不是在map

These two imply different complexities for most operations on the two. 这两者对于两者的大多数操作意味着不同的复杂性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM