简体   繁体   English

如何获取哈希值,C ++ hash_map

[英]how to get hash value, c++ hash_map

I'd like to access the hash value for a c++ hash_map. 我想访问C ++ hash_map的哈希值。 I tried: 我试过了:

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

The last line won't compile: 最后一行不会编译:

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

So obviously I don't know how to use the hasher function. 所以很明显我不知道如何使用哈希函数。 If anyone has a tip, it will be greatly appreciated. 如果有人给小费,将不胜感激。

The old STL did not include a specialisation of hash for std::string , since std::string was not part of the STL. 旧的STL不包含std::stringhash专用化,因为std::string不属于STL。 The full list of specialisations provided by the STL is documented at http://www.sgi.com/tech/stl/hash.html . STL提供的专业领域的完整列表记录在http://www.sgi.com/tech/stl/hash.html上

The best option is probably to use the modern equivalent, std::unordered_map , or std::tr1::unordered_map if you can't use C++11. 最好的选择可能是使用现代等效项std::unordered_mapstd::tr1::unordered_map如果您不能使用C ++ 11)。

If you really need to use hash_map for some reason, then you could probably specialise it yourself: 如果由于某些原因确实需要使用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());
        }
    };
}

I can't find hash_map reference on cplusplus.com but reading this line: hash_map<string, int> 我在cplusplus.com上找不到hash_map参考,但阅读此行: hash_map<string, int>

I think you'are missing a template parameter here: const hash<string> hh 我认为您在这里缺少模板参数: const hash<string> hh

No? 没有?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM