具有不同哈希码的密钥存在于同一桶中。 C ++

时间:2016-03-23 06:14:59

标签: c++11 unordered-map

我创建了一个ordered_map并插入了以下元素

  typedef std::unordered_multimap<std::string,std::string> stringMap;   
  stringMap mymap;  
  mymap.insert( {  
            {"house","maison"},  
            {"apple","pomme"},  
            {"tree","arbre"},  
            {"book","livre"},  
            {"door","porte"},  
            {"grapefruit","pamplemousse"}  
            } );  

当我检查水桶时,我发现有7个水桶。

这是我读到的:
    un_ordered关联容器的元素被组织到存储桶中。具有相同哈希码的密钥出现在同一个桶中

但是当我打印密钥的哈希码时,我发现桶中存在具有不同哈希码的元素。

#include <iostream>
#include <string>
#include <unordered_map>
int main ()  
{  
  typedef std::unordered_multimap<std::string,std::string> stringMap;   
  stringMap mymap;  
  mymap.insert( {  
            {"house","maison"},  
            {"apple","pomme"},  
            {"tree","arbre"},  
            {"book","livre"},  
            {"door","porte"},  
            {"grapefruit","pamplemousse"},  
            } );  

  unsigned n = mymap.bucket_count();  
  unsigned s = mymap.size();  

  std::cout << "mymap has " << n << " buckets.\n";  
  std::cout << "mymap size " << s << " keys.\n";  

  stringMap::hasher fn = mymap.hash_function();  

  for (unsigned i=0; i<n; ++i)  
  {  
    std::cout << "bucket #" << i << " contains: " << std::endl;;  
    for (auto it = mymap.begin(i); it!=mymap.end(i); ++it)  
    {  
      std::cout << "[" << it->first << ":" << it->second << "] ";  
      std::cout << "KEY HASH VALUE: " << fn (it->first) << std::endl;  
    }  

    std::cout << "\n";  
  }  

  return 0;  
} 

任何人都可以告诉我,如果我遗漏任何东西以及为什么带有不同哈希码的元素并存在于同一个存储桶中。

结果:

mymap has 7 buckets.
mymap size 6 keys.
bucket #0 contains: 
[book:livre] KEY HASH VALUE: 4190142187
[house:maison] KEY HASH VALUE: 4227651036

bucket #1 contains: 

bucket #2 contains: 

bucket #3 contains: 
[grapefruit:pamplemousse] KEY HASH VALUE: 3375607049
[tree:arbre] KEY HASH VALUE: 335777326

bucket #4 contains: 

bucket #5 contains: 
[apple:pomme] KEY HASH VALUE: 2758877147

bucket #6 contains: 
[door:porte] KEY HASH VALUE: 3658195372

谢谢

1 个答案:

答案 0 :(得分:1)

这是正常的。如果您有32位哈希码,则不需要2 ^ 32个桶。相反,哈希码被映射到存储桶的索引。例如,如果您有7个存储桶,则项目可能使用存储桶#(hash%7)。因此,具有哈希码0,7,14,21,......等的项目都出现在同一个桶中。