简体   繁体   English

访问tr1 / unordered_map的固有类型哈希函数

[英]Accessing the intrinsic type hash functions for tr1/unordered_map

I'm messing around with the unordered_map class template, and I'd like to write a custom hasher for my class. 我搞砸了unordered_map类模板,我想为我的类写一个自定义的哈希器。 The documentation for it mentions that default hashing functions are provided for the intrinsic types. 它的文档提到为固有类型提供了默认哈希函数。 So, if you declare: 因此,如果您声明:

std::tr1::unordered_map<std::string, int> foo;

You automatically get a hasher defined for you. 您会自动为您定义一个哈希器。

There's a good example on here on how to provide a functor if you want a custom hash function. 如果要使用自定义哈希函数,这里有一个很好的示例,说明如何提供函子。

However, what if I have a complex class that has a std::string member that I would like to use as the key for insertion/deletion into the unordered_map ? 但是,如果我有一个复杂的类,该类具有std::string成员,我想将该成员用作将键插入/删除到unordered_map的键? I don't want to rewrite my own hasher. 我不想重写自己的哈希器。 I want to leverage what was already written for the std::string type. 我想利用已经为std::string类型编写的内容。

The default hash functor is provided by std::hash<T> which returns size_t . 默认的哈希函子由std::hash<T>提供,该函数返回size_t

So you can combine the hash from several members of the class eg by computing (std::hash<T>()(a) + prime * (std::hash<T>()(b) + prime * std::hash<T>()(c))) . 因此,您可以合并类中多个成员的哈希,例如通过计算(std::hash<T>()(a) + prime * (std::hash<T>()(b) + prime * std::hash<T>()(c)))

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

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