1

I want to create a hash table where I can store value with pointers as key. For example In C++ if we define a linked list as:

struct Node{
 int val;
 Node* next;
}

I can create a hash table with pointers of Node using std::unordered_map or std::map like:

unordered_map<Node*,int> um;
Node* a = (Node*)malloc(sizeof(Node));
um[a]=12;
cout<<um[a]<<endl //This prints 12

Now if I want to do this without the standard library how can I calculate the hash value for Node pointers?

François Andrieux
  • 28,148
  • 6
  • 56
  • 87
Ahsan Sadeeb
  • 59
  • 1
  • 7
  • First you need to define your hashing function. – Eugene Sh. Mar 06 '20 at 16:11
  • [What's the difference between “STL” and “C++ Standard Library”?](https://stackoverflow.com/questions/5205491/whats-the-difference-between-stl-and-c-standard-library) – François Andrieux Mar 06 '20 at 16:14
  • If you are writing your hash implementation, you may find [Coding up a Hash Table](http://www.sparknotes.com/cs/searching/hashtables/section3.rhtml) and [Hash tables - eternally confuzzled](http://eternallyconfuzzled.com/tuts/datastructures/jsw_tut_hashtable.aspx) useful. – David C. Rankin Mar 06 '20 at 16:15
  • @FrançoisAndrieux perhaps we just edit and use `"C++ containers"` instead of `"STL"`? (which is what I take it to mean...) – David C. Rankin Mar 06 '20 at 16:24
  • Side note: In C++ `malloc` carries some risk. It does not call constructors so complicated objects are left as ticking time-bombs, ready to explode as soon as you try to use them improperly initialized. Users of the code will likely use `delete` to instead of `free` to release the allocation, and Crom only knows how that will turn out. – user4581301 Mar 06 '20 at 16:32
  • https://en.cppreference.com/w/cpp/utility/hash – datenwolf Mar 06 '20 at 17:01

1 Answers1

5

Cast them to uintptr_t and then calculate the hash values for integers.

user253751
  • 57,427
  • 7
  • 48
  • 90
  • One more bit of useful information: The above works because pointers should already be unique identifiers. If they aren't you have other problems. – user4581301 Mar 06 '20 at 16:28