简体   繁体   中英

how to get hash value, c++ hash_map

I'd like to access the hash value for a 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. The full list of specialisations provided by the STL is documented at 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.

If you really need to use hash_map for some reason, then you could probably specialise it yourself:

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>

I think you'are missing a template parameter here: const hash<string> hh

No?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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