Linux 下hash_map的使用

34 篇文章 0 订阅

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值