为什么hash会将自身返回为哈希值?
我已经并排设置了一个哈希和一个哈希,而一个字符串的字符串按预期工作,而int一个产生自己的哈希值!
它应该如何工作?
hash<int> h;
for( int i=0 ; i<15 ; ++i )
{
cout << "int hash for " << i << " is " << h(i) << endl;
}
hash<string> hs;
for( int i=0; i<15; ++i) {
stringstream ss;
ss << i;
cout << "string hash for " << i << " is " << hs(ss.str()) << endl;
}
Run Code Online (Sandbox Code Playgroud)
结果是
+ g++-4.8 -std=c++11 -O2 -Wall -pedantic -Weffc++ -Wextra main.cpp
+ ./a.out
int hash for 0 is 0
int hash for 1 is 1
int hash for 2 is 2
int hash for 3 is 3
int hash for 4 is 4
int hash for 5 is 5
int hash for 6 is 6
int hash for 7 is 7
int hash for 8 is 8
int hash for 9 is 9
int hash for 10 is 10
int hash for 11 is 11
int hash for 12 is 12
int hash for 13 is 13
int hash for 14 is 14
string hash for 0 is 2297668033614959926
string hash for 1 is 10159970873491820195
string hash for 2 is 4551451650890805270
string hash for 3 is 8248777770799913213
string hash for 4 is 16215888864653804456
string hash for 5 is 7995238595416485409
string hash for 6 is 3835993668518112351
string hash for 7 is 905566266843721762
string hash for 8 is 17899137375351314596
string hash for 9 is 6623666755989985924
string hash for 10 is 2594088158685378223
string hash for 11 is 9717255990760309898
string hash for 12 is 11194622142508650503
string hash for 13 is 15638310844945205280
string hash for 14 is 1116181219906060362
Run Code Online (Sandbox Code Playgroud)
你可以看到它在运行:http: //coliru.stacked-crooked.com/a/0c0e1536d19c533f
为什么hash会将自身返回为哈希值?
很坦率,因为它可以.这是最有效的方法,它为整数提供了一个完美的哈希函数.你根本无法做到更好!
不要将对象的哈希值与您可能存储它的哈希中的槽索引混淆。哈希值只是对给定输入值的接近唯一数值的最佳尝试。
您的代码表明,对于您散列的每个整数值,都会返回一个唯一的散列值。
这是一个理想的哈希函数。
std::hash<int, std::string> hashTable;
hashTable[42] = "hello";
Run Code Online (Sandbox Code Playgroud)
42的哈希值为42。但是这个哈希中可能没有42个桶。operator[]
这里超载,并且将hash value
通过哈希分布(桶的数量)来限制,以确定将您放入哪个槽中。
key = 42
hashValue = 42
hashKey = 42 % m_bucket.size() // which bucket to look for this key in
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3613 次 |
最近记录: |