现在的位置: 首页 > 综合 > 正文

hash_map与unordered_map的使用

2012年10月28日 ⁄ 综合 ⁄ 共 2390字 ⁄ 字号 评论关闭

在使用hash_map的程序中,编译的时候会报出warning,

In file included from /usr/include/c++/4.4/ext/hash_map:60,
                 from hash_a.h:6,
                 from test.cpp:5:
/usr/include/c++/4.4/backward/backward_warning.h:28:2: warning: #warning This file includes at least one deprecated or antiquated header which may be removed without further notice at a future date.

提示说编译时使用-Wno-deprecated选项使得不再提示这种错误。

既然c++0x已经成为标准的一部分,我们何不使用新的标准提供的unordered_map呢?

先简单看一下hash_map的使用,需要自己实现字符串的hash函数和比较函数。如下,  

#include <string>
using std::string;
#include
<ext/hash_map>
using namespace __gnu_cxx;

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

struct str_compare{
int operator()(const string& a,const string& b) const {
return (a==b);
}
};

同样的,对unordered_map,也需要使用自己定义的hash函数和比较函数(对string似乎是支持的,不需要自己定义hash函数)。与hash_map不同的是,这里需要的是class类型的函数,其成员为hash函数和比较函数,需要是公有成员。

与hash_map相同的是,需要参数为const,函数为const。注意这两个const,缺少的时候会报出一长串的错误信息。如下, 

#include <string>
using std::string;
#include
<unordered_map>
using std::unordered_map;

unsigned
int JSHash(const char *str){
unsigned
int hash = 1315423911;
while (*str){
hash
^= ((hash << 5) + (*str++) + (hash >> 2));
}
return (hash & 0x7FFFFFFF);
}


class StrHash{
public:
size_t
operator()(const string& s) const {
return JSHash(s.c_str());
}
};

class StrCompare{
public:
bool operator()(const string& a,const string& b) const {
return (a==b);
}
};

当使用unordered_map的时候,编译的时候需要加上选项--std=c++0x。  

简单的测试程序如下,

int main(){
hash_map
<string,int,str_hash,str_compare> strMap;
string a,b;
a
= "abc";
strMap[a]
= 3;
a
= "abcde";
strMap[a]
= 5;
a
= "abdec";
strMap[a]
= 55;
b
= a;
if(strMap.find(b)!=strMap.end())
cout
<< strMap[b] << endl;
else
cout
<< "not found " << b << endl;

unordered_map
<string,int,StrHash,StrCompare> StrMap;
a
= "abc";
StrMap[a]
= 3;
a
= "abcde";
StrMap[a]
= 5;
a
= "abdec";
StrMap[a]
= 55;
b
= a;
if(StrMap.find(b)!=StrMap.end())
cout
<< StrMap[b] << endl;
else
cout
<< "not found " << b << endl;

unordered_map
<string,int> theMap;
a
= "abc";
theMap[a]
= 3;
a
= "abcde";
theMap[a]
= 5;
a
= "abdec";
theMap[a]
= 55;
b
= a;
if(theMap.find(b)!=theMap.end())
cout
<< theMap[b] << endl;
else
cout
<< "not found " << b << endl;


return 0;
}

unordered_map在cplusplus上没有找到类的说明,在msdn上可以找到,

http://msdn.microsoft.com/en-us/library/bb982522.aspx

对Hash函数,有两个地方写的比较好,链接如下,

http://www.cppblog.com/bellgrade/archive/2009/10/06/97926.aspx

http://www.byvoid.com/blog/string-hash-compare/

关于unordered_map的一些参考,

http://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.3/a01312.html

http://en.wikipedia.org/wiki/Unordered_map_(C%2B%2B)

unordered_map的使用的参考,

http://www.cppblog.com/newplan/archive/2008/12/13/48912.html

共同学习下。

  

 

抱歉!评论已关闭.