Linux下使用hash_map 问题
1:头文件
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
{
};
struct str_equal
{
};
实现两个函数 一个是hash函数,一个是比较函数
hash_map <string, int,str_hash, str_equal> http_proxy_conn;
即可正确查找结果
hash_map <char *, int,str_hash, str_equal> http_proxy_conn的类型的应该也一样
- #include
<ext/hash_map> - #include
<iostream> - #include
<cstring> -
- using
namespace std; - using
namespace __gnu_cxx; -
- struct
eqstr{ -
bool operator()(const char *s1, const char *s2)const{ -
return strcmp(s1,s2) == 0; -
} - };
-
- int
main(){ -
hash_map<const char *,int,hash<const char *>,eqstr> months; -
months["january"] = 31; -
months["february"] = 28; -
months["march"] = 31; -
cout << "march -> " << months["march"] << endl; - }
- 不过没有测试
再加入类
#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 A.getvalue();
}
};
//2 define the equal function
struct equal_A{
bool operator()(const class ClassA & a1, const class ClassA & a2)const{
return
}
};
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