Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hashing pointers as Keys for unordered_map in C++ STL

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?

like image 624
Ammar Husain Avatar asked Aug 04 '14 18:08

Ammar Husain


People also ask

Can you use a pointer as a key to a map?

C++ standard provided specialisation of std::less for pointers, so yes you can safely use them as map keys etc.

Can you hash a pointer C++?

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.

Is unordered_map a hash table?

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.

Can unordered_map have pair as 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.


1 Answers

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.

like image 191
Mark Ransom Avatar answered Sep 30 '22 18:09

Mark Ransom