用過(guò)map吧?map提供一個(gè)很常用的功能,那就是提供key-value的存儲和查找功能。例如,我要記錄一個(gè)人名和相應的存儲,而且隨時(shí)增加,要快速查找和修改:
岳不群-華山派掌門(mén)人,人稱(chēng)君子劍張三豐-武當掌門(mén)人,太極拳創(chuàng )始人東方不?。谝桓呤?,葵花寶典...
#include <map>#include <string>using namespace std;...map<string, string> namemap;//增加。。。namemap["岳不群"]="華山派掌門(mén)人,人稱(chēng)君子劍";namemap["張三豐"]="武當掌門(mén)人,太極拳創(chuàng )始人";namemap["東方不敗"]="第一高手,葵花寶典";...//查找。。if(namemap.find("岳不群") != namemap.end()){ ...}速度永遠都滿(mǎn)足不了現實(shí)的需求。如果有100萬(wàn)條記錄,我需要頻繁進(jìn)行搜索時(shí),20次比較也會(huì )成為瓶頸,要是能降到一次或者兩次比較是否有可能?而且當記錄數到200萬(wàn)的時(shí)候也是一次或者兩次的比較,是否有可能?而且還需要和map一樣的方便使用。
答案是肯定的。這時(shí)你需要has_map. 雖然hash_map目前并沒(méi)有納入C++ 標準模板庫中,但幾乎每個(gè)版本的STL都提供了相應的實(shí)現。而且應用十分廣泛。在正式使用hash_map之前,先看看hash_map的原理。
hash_map基于hash table(哈希表)。 哈希表最大的優(yōu)點(diǎn),就是把數據的存儲和查找消耗的時(shí)間大大降低,幾乎可以看成是常數時(shí)間;而代價(jià)僅僅是消耗比較多的內存。然而在當前可利用內存越來(lái)越多的情況下,用空間換時(shí)間的做法是值得的。另外,編碼比較容易也是它的特點(diǎn)之一。
其基本原理是:使用一個(gè)下標范圍比較大的數組來(lái)存儲元素??梢栽O計一個(gè)函數(哈希函數,也叫做散列函數),使得每個(gè)元素的關(guān)鍵字都與一個(gè)函數值(即數組下標,hash值)相對應,于是用這個(gè)數組單元來(lái)存儲這個(gè)元素;也可以簡(jiǎn)單的理解為,按照關(guān)鍵字為每一個(gè)元素“分類(lèi)”,然后將這個(gè)元素存儲在相應“類(lèi)”所對應的地方,稱(chēng)為桶。
但是,不能夠保證每個(gè)元素的關(guān)鍵字與函數值是一一對應的,因此極有可能出現對于不同的元素,卻計算出了相同的函數值,這樣就產(chǎn)生了“沖突”,換句話(huà)說(shuō),就是把不同的元素分在了相同的“類(lèi)”之中。 總的來(lái)說(shuō),“直接定址”與“解決沖突”是哈希表的兩大特點(diǎn)。
hash_map,首先分配一大片內存,形成許多桶。是利用hash函數,對key進(jìn)行映射到不同區域(桶)進(jìn)行保存。其插入過(guò)程是:
由此可見(jiàn),要實(shí)現哈希表, 和用戶(hù)相關(guān)的是:hash函數和比較函數。這兩個(gè)參數剛好是我們在使用hash_map時(shí)需要指定的參數。
#include <hash_map>#include <string>using namespace std;int main(){ hash_map<int, string> mymap; mymap[9527]="唐伯虎點(diǎn)秋香"; mymap[1000000]="百萬(wàn)富翁的生活"; mymap[10000]="白領(lǐng)的工資底線(xiàn)"; ... if(mymap.find(10000) != mymap.end()){ ... }template <class _Key, class _Tp, class _HashFcn = hash<_Key>,class _EqualKey = equal_to<_Key>,class _Alloc = __STL_DEFAULT_ALLOCATOR(_Tp) >class hash_map{ ...}...hash_map<int, string> mymap;//等同于:hash_map<int, string, hash<int>, equal_to<int> > mymap;
struct hash<int> { size_t operator()(int __x) const { return __x; }};struct hash<char*>struct hash<const char*>struct hash<char> struct hash<unsigned char> struct hash<signed char>struct hash<short>struct hash<unsigned short> struct hash<int> struct hash<unsigned int>struct hash<long> struct hash<unsigned long>
struct str_hash{ size_t operator()(const string& str) const { unsigned long __h = 0; for (size_t i = 0 ; i < str.size() ; i ++) __h = 5*__h + str[i]; return size_t(__h); }};//如果你希望利用系統定義的字符串hash函數,你可以這樣寫(xiě):struct str_hash{ size_t operator()(const string& str) const { return return __stl_hash_string(str.c_str()); }};現在可以對開(kāi)頭的"岳不群"進(jìn)行哈?;?

map<string, string> namemap; //改為:hash_map<string, string, str_hash> namemap;
你或許會(huì )問(wèn):比較函數呢?別著(zhù)急,這里就開(kāi)始介紹hash_map中的比較函數。
//本代碼可以從SGI STL//先看看binary_function 函數聲明,其實(shí)只是定義一些類(lèi)型而已。template <class _Arg1, class _Arg2, class _Result>struct binary_function { typedef _Arg1 first_argument_type; typedef _Arg2 second_argument_type; typedef _Result result_type;};//看看equal_to的定義:template <class _Tp>struct equal_to : public binary_function<_Tp,_Tp,bool>{ bool operator()(const _Tp& __x, const _Tp& __y) const { return __x == __y; }};struct mystruct{ int iID; int len; bool operator==(const mystruct & my) const{ return (iID==my.iID) && (len==my.len) ; }}; struct compare_str{ bool operator()(const char* p1, const char*p2) const{ return strcmp(p1,p2)==0; }}; typedef hash_map<const char*, string, hash<const char*>, compare_str> StrIntMap;StrIntMap namemap;namemap["岳不群"]="華山派掌門(mén)人,人稱(chēng)君子劍";namemap["張三豐"]="武當掌門(mén)人,太極拳創(chuàng )始人";namemap["東方不敗"]="第一高手,葵花寶典";
現在知道如何選擇了嗎?權衡三個(gè)因素: 查找速度, 數據量, 內存使用。
這里還有個(gè)關(guān)于hash_map和map的小故事,看看:http://dev.csdn.net/Develop/article/14/14019.shtm
-bash-2.05b$ cat my.cpp#include <hash_map>#include <string>#include <iostream>using namespace std;//define the classclass ClassA{ public: ClassA(int a):c_a(a){} int getvalue()const { return c_a;} void setvalue(int a){c_a;} private: int c_a;};//1 define the hash functionstruct hash_A{ size_t operator()(const class ClassA & A)const{ // return hash<int>(classA.getvalue()); return A.getvalue(); }};//2 define the equal functionstruct equal_A{ bool operator()(const class ClassA & a1, const class ClassA & a2)const{ return a1.getvalue() == a2.getvalue(); }};int main(){ hash_map<ClassA, string, hash_A, equal_A> hmap; ClassA a1(12); hmap[a1]="I am 12"; ClassA a2(198877); hmap[a2]="I am 198877"; cout<<hmap[a1]<<endl; cout<<hmap[a2]<<endl; return 0;}-bash-2.05b$ make myc++ -O -pipe -march=pentiumpro my.cpp -o my-bash-2.05b$ ./myI am 12I am 198877typedef map<Key, Value> KeyMap;當你希望使用hash_map來(lái)替換的時(shí)候,只需要修改: 其他的基本不變。當然,你需要注意是否有Key類(lèi)型的hash函數和比較函數。
聯(lián)系客服