简体   繁体   English

std::unordered_map 如何表现? [C++]

[英]How std::unordered_map Behaves? [C++]

I was reading about C++ unordered_map and have few questions which I can't answer clearly.我正在阅读有关 C++ unordered_map 的内容,并且有几个我无法清楚回答的问题。

I have noticed that unordered_map puts one element per index and not multiple (hash tables can be implemented using on of these methods to solve 2 elements being mapped to same index)我注意到 unordered_map 每个索引放置一个元素而不是多个(可以使用这些方法中的一种来实现哈希表,以解决映射到同一索引的 2 个元素)

  1. If an element with key A in the map, and I insert another one it will override the previous element right?如果 map 中带有键 A 的元素,我插入另一个元素,它将覆盖前一个元素,对吗? (no matter if the values match or not). (无论值是否匹配)。

  2. Is there an option to change the behavior of unordered_map so it can contains multiple elements per index like I explained above?是否有一个选项可以改变 unordered_map 的行为,以便它可以包含每个索引的多个元素,就像我上面解释的那样?

  3. I have noticed from my code that unordered_map gets bigger by one every-time I insert a new element but that's really bad, I learnt in hash table we need to multiply size by 2 every-time it's needed so complexity for inserting is O(1) Amortized and not O(n).我从我的代码中注意到,unordered_map 每次插入一个新元素时都会变大,但这真的很糟糕,我在 hash 表中了解到,我们需要每次需要将大小乘以 2,因此插入的复杂性是 O(1 ) 摊销而不是 O(n)。

  4. How can I give my unordered_map an initial size but with no elements?如何给我的 unordered_map 一个初始大小但没有元素? ie I know it will reach size 1000 so instead of making it bigger multiple times and doing heavy copying we can do it straightforward.即,我知道它会达到 1000 的大小,所以与其将其放大多次并进行大量复制,我们可以直接进行。

Let me shortly answer your questions让我简短地回答你的问题

  1. No, you cannot insert a new key.不,您不能插入新密钥。 The function will fail. function 将失败。 Keys must be unique.键必须是唯一的。
  2. No, there is no option.不,没有选择。 If you want to store multiple same keys, the you need to use a std::unordered_multimap instead如果要存储多个相同的键,则需要使用std::unordered_multimap
  3. You mix up bucket with number elements.您将存储桶与数字元素混合在一起。 Of course the mapwill grow, if you enter a new key.当然,如果您输入新的密钥,地图将会增长。 If there would be the same hash value for 2 different keys, then those would be stored in a bucket for the hash value.如果 2 个不同的键有相同的 hash 值,那么这些值将存储在 hash 值的存储桶中。
  4. This does not make that much sense.这没有多大意义。 See 3. And, also logically: A map contains keys.参见 3。而且,从逻辑上讲:map 包含密钥。 And if a key is in, then you cannot overwrite.如果有键,则无法覆盖。 However, you may use its reserve function, to allocate internal space.但是,您可以使用其reserve的 function 来分配内部空间。 . . . .

All this is explained in the CPP Reference.所有这些都在 CPP 参考中进行了解释。 Please see here请看这里

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

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