Http://blog.sina.com.cn/s/blog_73eb956401019cq1.html
Hash_map in Linux
1: header file
# If 0
# If _ gnuc __> 2
# Include <EXT/hash_set>
# Include <EXT/hash_map>
Using namespace _ gnu_cxx;
# Else
# Include # Include Using namespace stdext;
# Endif
# Endif
2: map with string or char * as key is not supported. If hash_map <char *, int> http_proxy_conn is used;
In comparison, the string address is actually compared, not the string itself.
Hash_map <string, int> http_proxy_conn is equivalent
Hash_map <string, Int, hash, equal> http_proxy_conn, the last two parameters are the default system
Solution:
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;
}
};
Implement two functions: a hash function and a comparison function.
Hash_map <string, Int, str_hash, str_equal> http_proxy_conn;
You can find the correct result.
Hash_map <char *, Int, str_hash, str_equal> the same type should be used for http_proxy_conn.
- # Include<EXT/hash_map>
- # Include<Iostream>
- # Include<Cstring>
-
- UsingNamespaceSTD;
- UsingNamespace_ Gnu_cxx;
-
- StructEqstr {
- Bool Operator ()(ConstChar * S1,ConstChar * S2)Const {
- ReturnStrcmp (S1, S2)=0;
- }
- };
-
- Int Main (){
- Hash_map <ConstChar *,Int, Hash <constChar *>, Eqstr>Months;
- Months ["January"]=31;
- Months ["February"]=28;
- Months ["March"]=31;
- Cout<"March->" <Months ["March"]<Endl;
- }
- But not tested
Add another class
# Include # Include <string>
# Include <iostream>
Using namespace STD;
// Define the class
Class classa {
Public:
Classa (int A): c_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 {
//ReturnHash <int> (classa. getvalue ());
Return A. getvalue ();
}
};
// 2 define the equal Function
Struct defaults _a {
Bool operator () (const class classa & A1, const class classa & A2) const {
ReturnA1.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 Cout Return 0;
}
In the end, it was too troublesome to change it to map. string can be used as the key.