-2

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

Satender346
  • 352
  • 1
  • 3
  • 15
  • 1
    There are plenty of examples out there. There's one in K&R. – luser droog Aug 05 '13 at 07:01
  • 1
    FYI `std::map` is _not_ a hash map. It's a binary tree. `std::unordered_map` is a hash map. Oh, and come back when you've looked up the algorithm and written some code. – Useless Aug 05 '13 at 07:43

1 Answers1

7

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.

Phil Pill
  • 303
  • 2
  • 14
Giuseppe Pes
  • 7,772
  • 3
  • 52
  • 90
  • thanks but above example i have already seen they are quite complex. is any alternative method ? to store dynamic unique key and value – Satender346 Aug 05 '13 at 07:38
  • I have updated my answer. Try to read the tutorial I have linked. It is as thorough as easy to understand. I hope it is useful. – Giuseppe Pes Aug 05 '13 at 08:10