Hash 一般譯作「散列」,也有人直接音譯為「哈希」,指的是把任意長度的輸入透過散列演算法變換成固定長度的輸出。這是一種壓縮映射:散列值空間通常遠小於輸入空間,不同輸入可能得到相同輸出,也不可能從散列值反推唯一輸入。簡單說,就是將任意長度的訊息壓縮成固定長度摘要的函式。
實作在 backward/hash_fun.h,命名空間 __gnu_cxx:
inline size_t
__stl_hash_string(const char* __s)
{
unsigned long __h = 0;
for ( ; *__s; ++__s)
__h = 5 * __h + *__s;
return size_t(__h);
}
並基於這個演算法特化了多個版本:
hash<char*> hash<const char*> hash<char> hash<unsigned char> hash<signed char> hash<short> hash<unsigned short> hash<int> hash<unsigned int> hash<long> hash<unsigned long>
標準庫沒有提供 string 版本,需要自己補一個特化:
namespace __gnu_cxx
{
template <>
struct hash<string>
{
size_t operator()(const string &s) const
{ return __stl_hash_string(s.c_str()); }
};
}
特點與用途:FNV 能快速散列大量資料並保持較低的碰撞率,高度分散的特性使它特別適合處理彼此非常相近的字串,例如 URL、主機名、檔名、文字、IP 位址等。
它位於 std::tr1 命名空間,包含 tr1/functional 即可,實作在 tr1_impl/functional_hash.h:
// 泛用版本(sizeof(size_t) 不為 4 或 8 時)
template<std::size_t = sizeof(std::size_t)>
struct Fnv_hash
{
static std::size_t
hash(const char* first, std::size_t length)
{
std::size_t result = 0;
for (; length > 0; --length)
result = (result * 131) + *first++;
return result;
}
};
template<>
struct Fnv_hash<4>
{
static std::size_t
hash(const char* first, std::size_t length)
{
std::size_t result = static_cast<std::size_t>(2166136261UL);
for (; length > 0; --length)
{
result ^= (std::size_t)*first++;
result *= 16777619UL;
}
return result;
}
};
template<>
struct Fnv_hash<8>
{
static std::size_t
hash(const char* first, std::size_t length)
{
std::size_t result = static_cast<std::size_t>(14695981039346656037ULL);
for (; length > 0; --length)
{
result ^= (std::size_t)*first++;
result *= 1099511628211ULL;
}
return result;
}
};
在此之上又實作了各型別的 hash 版本,包含 string 與 wstring。
#include <iostream>
#include <string>
#include <tr1/functional>
int main()
{
std::string name = "feng feng feng";
// 直接呼叫 Fnv_hash
std::cout << std::tr1::_Fnv_hash<1>::hash(name.c_str(), name.size()) << std::endl;
std::cout << std::tr1::_Fnv_hash<4>::hash(name.c_str(), name.size()) << std::endl;
std::cout << std::tr1::_Fnv_hash<8>::hash(name.c_str(), name.size()) << std::endl;
// string / wstring / bool / float / double / short / int / long
std::cout << std::tr1::hash<std::string>()(name) << std::endl;
std::wstring age = L"22222";
std::cout << std::tr1::hash<std::wstring>()(age) << std::endl;
std::cout << std::tr1::hash<int>()(24) << std::endl;
return 0;
}
說明:gcc 4.8 以上完整支援 C++11,我這裡用的是 4.7。在 4.7 中 tr1/functional 所對應的 functional 標頭檔已直接在搜尋路徑上,可以改成 #include <functional>,這樣就不必再寫 std::tr1 命名空間,直接放在 std 下即可,編譯時多帶一個參數:
g++ -std=c++0x myHash.cpp