[英]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 个元素)
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). (无论值是否匹配)。
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 的行为,以便它可以包含每个索引的多个元素,就像我上面解释的那样?
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)。
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让我简短地回答你的问题
std::unordered_multimap
instead如果要存储多个相同的键,则需要使用std::unordered_multimap
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.