简体   繁体   English

STL如何散列unordered_map <>的键?

[英]How does STL work to hash the key of unordered_map<>?

I am trying to implement a hash map myself, and i want to use an array to do that. 我正在尝试自己实现哈希映射,并且我想使用数组来做到这一点。 But the problem i am currently dealing with is how to hash the key to an hash value. 但是我当前正在处理的问题是如何将键哈希值哈希值。 Do i need to used different methods to do the hashing given different types like 'int', 'char', 'string', '*pointer', or is there a way that i can do that all together? 我是否需要使用不同的方法对给定的不同类型(例如'int','char','string','* pointer')进行哈希处理,还是有一种方法可以将它们一起完成? I was trying to use reinterpret_cast(expression) , but it doesn't work for 'char'. 我试图使用reinterpret_cast(expression) ,但不适用于'char'。

Thanks in advance. 提前致谢。

STL uses a template class which is already defined for most of the basic types. STL使用已经为大多数基本类型定义的模板类。 Indeed, in real time scenarios, you must implement it for your own data type if you fall out of these bounds. 确实,在实时场景中,如果超出这些范围,则必须针对自己的数据类型实现它。

The template class is hash<T> , take a look here . 模板类是hash<T>在这里看看。

Mind that templates doesn't work as Java generics, you "fill the hole" with a template specialization for your specific type, you don't have an implementation which works for all of them in this case (unless you define a common base class for the objects you are going to store inside the map, or, as suggested in the comment, you go lower level, and take the raw bytes of the class variables). 请注意,模板不能作为Java泛型使用,您需要为特定类型的模板专门化来“填补空缺”,在这种情况下,您没有一种适用于所有模板的实现(除非您定义通用的基类)对于要存储在地图中的对象,或者按照注释中的建议,您将移至较低级别,并获取类变量的原始字节)。

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

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