问题描述
我有一个名为Foo的类,它私有地不超过4字节int。如果我将其值返回为8字节的size_t,我是否会搞砸unordered_map<>
还是其他?我可以用return foo + foo << 32;
之类的东西填充所有位。会更好,还是会更糟,因为所有哈希现在都是0x100000001的倍数?还是return ~foo + foo << 32;
会使用全部64位并且也没有公因子呢?
namespace std {
template<> struct hash<MyNamespace::Foo> {
typedef size_t result_type;
typedef MyNamespace::Foo argument_tupe;
size_t operator() (const MyNamespace::Foo& f ) const { return (size_t) f.u32InternalValue; }
};
}
解决方法
将增量uint32_t
转换为uint64_t
的效果很好
unordered_map
将为哈希表逐步保留空间。
密钥的较低有效位用于确定存储桶位置,在4个条目/存储桶的示例中,使用较低有效的2位。 具有相同存储桶(存储桶数的倍数)的键的元素链接在一个链表中。带有负载因子的概念。
// 4 Buckets example
******** ******** ******** ******** ******** ******** ******** ******XX
bucket 00 would contains keys like {0,256,200000 ...}
bucket 01 would contains keys like {1,513,4008001 ...}
bucket 10 would contains keys like {2,130,10002 ...}
bucket 11 would contains keys like {3,259,1027,20003,...}
如果您尝试在存储桶中保存其他值,并且其加载因子超过了限制,则将调整表的大小(例如,尝试在具有load_factor = 1.0的4存储桶表中保存第5个元素)。 / p>
因此:
拥有一个uint32_t
或一个uint64_t
键对您几乎没有影响,直到您到达2 ^ 32个元素的哈希表为止。
会更好,还是会更糟,因为所有哈希现在都是0x100000001的倍数?
直到达到32位溢出(2 ^ 32)哈希表,这才有影响。
增量uint32_t和uint64_t之间的良好密钥转换:
key64 = static_cast<uint64>(key32);
增量uint32_t和uint64_t之间的密钥转换:
key64 = static_cast<uint64>(key32)<<32;
最好是尽可能地保持键,避免一次又一次地使用相同系数的哈希值。例如。在下面的代码中,全为7的键将发生冲突,直到将其调整为16个存储桶为止。
https://onlinegdb.com/r1N7TNySv
#include <iostream>
#include <unordered_map>
using namespace std;
// Print to std output the internal structure of an unordered_map.
template <typename K,typename T>
void printMapStruct(unordered_map<K,T>& map)
{
cout << "The map has " << map.bucket_count()<<
" buckets and max load factor: " << map.max_load_factor() << endl;
for (size_t i=0; i< map.bucket_count(); ++i)
{
cout << " Bucket " << i << ": ";
for (auto it=map.begin(i); it!=map.end(i); ++it)
{
cout << it->first << " ";
}
cout << endl;
}
cout << endl;
}
// Print the list of bucket sizes by this implementation
void printMapResizes()
{
cout << "Map bucket counts:"<< endl;
unordered_map<size_t,size_t> map;
size_t lastBucketSize=0;
for (size_t i=0; i<1024*1024; ++i)
{
if (lastBucketSize!=map.bucket_count())
{
cout << map.bucket_count() << " ";
lastBucketSize = map.bucket_count();
}
map.emplace(i,i);
}
cout << endl;
}
int main()
{
unordered_map<size_t,size_t> map;
printMapStruct(map);
map.emplace(0,0);
map.emplace(1,1);
printMapStruct(map);
map.emplace(72,72);
map.emplace(17,17);
printMapStruct(map);
map.emplace(7,7);
map.emplace(14,14);
printMapStruct(map);
printMapResizes();
return 0;
}
注意存储桶数:
在上面的示例中,存储区计数如下:
1 3 7 17 37 79 167 337 709 1493 3209 6427 12983 26267 53201 107897 218971 444487 902483 1832561
这似乎是有意遵循一系列质数(以最小化冲突)。我不知道背后的功能。