menu

秋梦无痕

一场秋雨无梦痕,春夜清风冻煞人。冬来冷水寒似铁,夏至京北蟑满城。

Avatar

__gnu_cxx::hash_map使用string和long long做key的问题

Q: 使用__gnu_cxx::hash_map时,如下代码可以正常运行:

#include <iostream>
#include <ext/hash_map>

__gnu_cxx::hash_map <const char *, int> months;
int main(void) {
months["jan"] = 31;
months["oct"] = 31;
return 0;
}

下面的代码编译不通过:

#include <iostream>
#include <string>
#include <ext/hash_map>

__gnu_cxx::hash_map <std::string, int> months;
int main(void) {
months["jan"] = 31;
months["oct"] = 31;
return 0;
}

原因是hash_map不是标准的库,对std::string和long long的支持有点问题。

A: 解决办法,添加如下代码:

#include <ext/hash_map>
namespace __gnu_cxx
{
template<> struct hash< std::string >
{
size_t operator()( const std::string& x ) const
{
return hash< const char* >()( x.c_str() );
}
};

template<> struct hash<long long>
{
size_t operator()(long long x) const
{
return x;
}
};
}