我想访问 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&)
所以显然我不知道如何使用哈希函数。如果有人有提示,将不胜感激。
最佳答案
旧的 STL 不包括 std::string
的 hash
特化,因为 std::string
不是STL。 STL 提供的完整专业列表记录在 http://www.sgi.com/tech/stl/hash.html 中。 .
最好的选择可能是使用现代的等价物,std::unordered_map
,或者如果您不能使用 C++,则使用 std::tr1::unordered_map
11.
如果出于某种原因你真的需要使用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());
}
};
}
关于c++ - 如何获取哈希值,c++ hash_map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11264675/