Search code examples
c++chashmaphashcode

implement hash map in c


i need to impediment key and value in c like we used in c++ using map.

Please share simplest example to store unique key and value in store in c. key my be any string and value will be string.

Thanks


Solution

  • Creating a hash map requires a bit of work, but is definitely an interesting thing to do.

    The general approach to build a hash map is to create an array called buckets that contains keys and values. However, this structure is not able to deal with collisions. A collision between two values may arise when different keys are assigned by the hash function to the same value.

    To address this problem a third field, usually a pointer, is added to the bucket. When a collision arises, the new value is added in the data structure pointed at by the third field, usually a linked list or binary tree. For more information about how to resolve collisions, read this link.

    An example of the Hash map Structure described above (note the collision at index 153): Hash map Structure

    To access the hash table, a custom hash function, which returns an integer which identifies the array index location, is applied to the key. Finally, you check if the key used to access the element and the key stored in the array at the index returned by the hash function match. If they do, you have found the right element.

    This is just an example; you can find different ways to implement a hash map.

    In addition, this question has already been asked here.