index > STL > unordered_map
簡介
內部實現哈希的map,相對於一般map來說,理論上更快。
應用基本和普通map類似,甚至有時候會讓人覺得unordered_map更符合我們的需求,因爲我們unordered_map的修改查詢很快,但遍歷很慢,一般我們開map也不用到遍歷。
unordered_map對key的要求是需要實現其哈希過程,默認的哈希支持整數類型的key。
缺陷與改進
理論上更快的,但有例外,而且很可能會影響到一些特定樣例的運行時間。
因爲一般的編譯器,給unordered_map默認的哈希表是固定的,當然細節挺複雜,詳細可以看參考裏的那篇博客。
筆者就說一個很簡陋的理解:
默認的哈希在處理衝突的時候,是藉助固定的哈希表來偏移的,衝突越多需要的時間越多。當有針對性地hack時,最差會退化成 的過程。
爲了解決這個問題,一般都會自寫哈希過程, 下面是大佬的優秀實現:
struct custom_hash {
static uint64_t splitmix64(uint64_t x) {
// http://xorshift.di.unimi.it/splitmix64.c
x += 0x9e3779b97f4a7c15;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
return x ^ (x >> 31);
}
size_t operator()(uint64_t x) const {
static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
return splitmix64(x + FIXED_RANDOM);
}
};
unordered_map<long long, int, custom_hash> safe_map;
可以說,哈希得更好,能提高性能。
參考
Blowing up unordered_map, and how to stop getting hacked on it by neal
C++ STL: Order of magnitude faster hash tables with Policy Based Data Structures by Chilli