Linux 下hash_map的使用

來源:互聯網
上載者:User

http://blog.sina.com.cn/s/blog_73eb956401019cq1.html

 

Linux下使用hash_map 問題

1:標頭檔

#if 0
 #if __GNUC__>2
 #include <ext/hash_set>
 #include <ext/hash_map>
  using namespace __gnu_cxx;
 #else
 #include <hash_set>
 #include <hash_map>
  using namespace stdext;
 #endif

#endif

 

2:不支援string或char *為key的map 若用這個hash_map <char*, int> http_proxy_conn;

則比較時其實比較的是字串的地址,而不是字串本身

hash_map <string, int> http_proxy_conn等價於

hash_map <string, int, hash, equal> http_proxy_conn,後兩個參數為預設系統的

解決方案:

struct str_hash
{
 size_t operator()(const string& str) const
 {
   return __stl_hash_string(str.c_str());
 }
};

struct str_equal
{
    bool operator()(const string& s1,const string& s2) const
    {
     return s1==s2;
    }
};

實現兩個函數 一個是hash函數,一個是比較函數

hash_map <string, int,str_hash, str_equal> http_proxy_conn;

即可正確尋找結果

 

hash_map <char *, int,str_hash, str_equal> http_proxy_conn的類型的應該也一樣

 

  1. #include <ext/hash_map>
      
  2. #include <iostream>   
  3. #include <cstring>   
  4.   
  5. using namespace std;    
  6. using namespace __gnu_cxx;   
  7.   
  8. struct eqstr{   
  9.     bool operator()(const char *s1, const char *s2)const{
      
  10.         return strcmp(s1,s2) == 0;   
  11.     }   
  12. };   
  13.   
  14. int main(){   
  15.     hash_map<const char *,int,hash<const char *>,eqstr> months;
      
  16.     months["january"] = 31;   
  17.     months["february"] = 28;   
  18.     months["march"] = 31;   
  19.     cout << "march -> " << months["march"] << endl;   
  20. }  
  21. 不過沒有測試

再加入類

#include <hash_map>
#include <string>
#include <iostream>
using namespace std;
//define the class
class 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 function
struct hash_A{
size_t operator()(const class ClassA & A)const{
//  return  hash<int>(classA.getvalue());
return A.getvalue();
}
};
//2 define the equal function
struct 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;
}

到最後嫌麻煩,直接改成map了,可以支援string為key

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.