简体   繁体   English

对C ++ unordered_map和哈希冲突感到困惑

[英]Confused about C++ unordered_map and hash collision

I've read that unordered_map places elements with the same hash in buckets and that's how it handles hash collisions. 我已经读过unordered_map在桶中放置具有相同散列的元素,这就是它处理散列冲突的方式。 However, when I checked the insert function , it says: 但是,当我检查插入功能时 ,它说:

Each element is inserted only if its key is not equivalent to the key of any other element already in the container 仅当每个元素的键不等同于容器中已有的任何其他元素的键时,才会插入每个元素

Does that mean that I cannot insert an element with the same hash?.. I'm supposed to be able to insert an element with a new hash since the unordered_map structure can handle collisions, right?.. I think I may be missing something. 这是否意味着我不能插入具有相同哈希的元素?..我应该能够插入一个带有新哈希的元素,因为unordered_map结构可以处理冲突,对吧?我想我可能会遗漏一些东西。

It's certainly possible for those statements to be consistent, once you realise that the hash isn't necessarily the key. 这当然是可能的这些语句是一致的,一旦你意识到哈希不一定是关键。

A group of distinct keys may generate the same hash value, so be stored in the same bucket, but that still allows for the restriction that duplicate keys are disallowed. 一组不同的密钥可以生成相同的散列值,因此存储在同一个存储桶中,但仍然允许禁止重复密钥的限制。

For example, let's say you have a friends collection using first name as the key. 例如,假设您使用名字作为密钥的friends集合。 The hash function is (a rather simplistic) "use the first letter of the name. 哈希函数是(相当简单)“使用名称的第一个字母。

So, while Albert, Andrew, Adam, Bill, Benny and Chloe are six different keys, they only account for three different hash values: 因此,虽然Albert,Andrew,Adam,Bill,Benny和Chloe是六个不同的键,但它们只占三个不同的哈希值:

          A                 B            C    (buckets)
   ______/|\_____          / \           |
  /       |      \        /   \          |
Albert  Andrew  Adam    Bill  Benny    Chloe  (keys)

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

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