简体   繁体   中英

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? I was trying to use reinterpret_cast(expression) , but it doesn't work for 'char'.

Thanks in advance.

STL uses a template class which is already defined for most of the basic types. 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 .

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).

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