I posted a similar quetion regarding using pointers as Keys on maps in C++ STL. How are pointers hashed in unordered_maps when used as Keys. More specifically if I define:
std::unordered_map< CustomClass*, int > foo;
Would the default C++ std::hash implementation work to handle these pointers? Is it safe to use? Is this good practice?
C++ standard provided specialisation of std::less for pointers, so yes you can safely use them as map keys etc.
Is it safe to use? Is this good practice? you probably mean std::unordered_map and the answer is practicaly the same: you can use pointers if you really mean to hash pointers (and not the object they point to). You can as well implement your own hash (or hash-redirection) to work with the pointed-to objects.
Unordered_map IS a hash table actually. You may want to use a better example as, as is the second insert will fail since it has the same key.
Unordered Map does not contain a hash function for a pair like it has for int, string, etc, So if we want to hash a pair then we have to explicitly provide it with a hash function that can hash a pair. unordered_map can takes upto 5 arguments: Key : Type of key values. Value : Type of value to be stored against the key.
std::hash<T*>
is defined but the details of how it operates are implementation dependent. It will certainly be safe to use, and I'd consider it good practice - as long as it's the pointer you need as the key, and not the object contents itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With