c++ - 如何获取哈希值,c++ hash_map

标签 c++ stl hashmap

我想访问 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::stringhash 特化,因为 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/

相关文章:

c++ - stable_sort 的自定义比较函数

c++ - 从 DLL 导出 STL 类 - 为什么返回类型没有警告?

java - 如何将新的键值添加到java中现有的List Map对象

rust - 如何创建带有类型删除键的 HashMap?

c++ - Boost 解析日期/时间字符串并产生 .NET 兼容的 Ticks 值

c++ - 为什么 shared_ptr 在函数中返回时没有隐式转换为 boolean 值?

c++ - 用于成对比较和跟踪最大/最长序列的STL算法

jsp - 在struts 2中迭代hashmap并根据其值检查或取消选中复选框

不同类型的 C++ 映射赋值重载

c++ - vera++ 抛出错误 : cannot open profile description for profile default