2012-06-29 36 views
0

我想訪問C++ hash_map的散列值。我想:如何獲取散列值,C++ hash_map

__gnu_cxx::hash_map<string, int> my_table; 
const hash<string> hh = my_table.hash_funct(); 
string s("hello"); 
size_t j = hh(s); 

最後一行將無法編譯:

no match for call to '(const __gnu_cxx::hash<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >) (std::string&) 

所以,很顯然,我不知道如何使用散列器功能。如果有人有小費,將不勝感激。

回答

0

我找不到cplusplus.com的hash_map參考,但閱讀這條線:hash_map<string, int>

我覺得you'are這裏缺少一個模板參數:const hash<string> hh

沒有?

+0

這是從古老的STL庫,在http://www.sgi.com/tech/記錄stl和'hash'只有一個模板參數。 –

4

由於std::string不是STL的一部分,舊的STL沒有包含hash的專門化std::string。 STL提供的完整專業列表記錄在http://www.sgi.com/tech/stl/hash.html

如果您不能使用C++ 11,最好的選擇可能是使用現代等價物std::unordered_mapstd::tr1::unordered_map

如果你真的需要使用hash_map出於某種原因,那麼你很可能自己擅長的:

namespace __gnu_cxx { 
    template <> struct hash<std::string> { 
     size_t operator()(std::string const & s) const { 
      hash<const char *> h; 
      return h(s.c_str()); 
     } 
    }; 
}