#眉標=Boost #副標=「Boost技術與應用」系列文章(5) #大標=Boost.Hash #作者=文圖/侯捷 #引言= #圖6 SGI STL的 定義了一個 'hash' functor用來計算hash code template struct hash { }; //泛化版本 //以下皆為特化版本,為基礎型別如char,short,int,long…服務。 template<> struct hash { size_t operator()(char x) const { return x; } }; template<> struct hash { size_t operator()(unsigned char x) const { return x; } }; template<> struct hash { size_t operator()(unsigned char x) const { return x; } }; template<> struct hash { size_t operator()(short x) const { return x; } }; template<> struct hash { size_t operator()(unsigned short x) const { return x; } }; template<> struct hash { size_t operator()(int x) const { return x; } }; template<> struct hash { size_t operator()(unsigned int x) const { return x; } }; template<> struct hash { size_t operator()(long x) const { return x; } }; template<> struct hash { size_t operator()(unsigned long x) const { return x; } }; #圖7 SGI STL的 定義了一個__stl_hash_string用來計算 C-style string的hash code。 inline size_t __stl_hash_string(const char* s) { unsigned long h = 0; for ( ; *s; ++s) h = 5*h + *s; return size_t(h); } template<> struct hash { size_t operator()(const char* s) const { return __stl_hash_string(s); } }; template<> struct hash { size_t operator()(const char* s) const { return __stl_hash_string(s); } }; ==<反灰>=========== #include #include #include #include #include #include #include ================ ==<反灰>=========== hash_value(const T (&v)[N]) //(1) ================ ==<反灰>=========== hash_value(std::basic_string, A> const& v) ================ ==<反灰>=========== hash_value(std::pair const& v) //(3) ================ ==<反灰>=========== hash int_hash; hash uint_hash; hash long_hash; hash ulong_hash; hash float_hash; hash double_hash; hash ld_hash; int_hash(-5); //-5 (0xfffffffb) uint_hash(5); //5 long_hash(-50); //-50 (0xffffffce) ulong_hash(50); //50 (0x32) float_hash(5.0); //0x8994bfd3 double_hash(7.0); //0x2a581eed ld_hash(7.7); //0x0c07801a ================ ==<反灰>=========== namespace boost { std::size_t hash_value(book const& b) { boost::hash hasher; return hasher(b.id); } } ================ ==更多資訊=========== 以下是與本文相關的讀物或網上資源。 • Boost Libraries Documentation, from http://www.boost.org • 《STL源碼剖析》by侯捷,第五章「關聯式容器」。 ================ ==作者簡介 =========== 侯捷 資訊顧問、專欄主筆、大學執教。常著文章自娛,頗示己志。 侯捷網站:http://www.jjhou.com(繁體) 北京鏡站:http://jjhou.csdn.net(簡體) 永久郵箱:jjhou@jjhou.com ================