简体   繁体   中英

if the index are not integer how we can insert in hash table in c++

If I have 4 data like 1,2,3,4 and the hash table size is 5 then we can insert it according to the index, and search the item based on the index with the hash function like below.

h(x)= x%5

Insert function:

void insert(int key,int data) {
   struct DataItem *item = (struct DataItem*) malloc(sizeof(struct DataItem));
   item->data = data;  
   item->key = key;     

   //get the hash 
   int hashIndex = hashCode(key);

   //move in array until an empty or deleted cell
   while(hashArray[hashIndex] != NULL && hashArray[hashIndex]->key != -1) {
      //go to next cell
      ++hashIndex;

      //wrap around the table
      hashIndex %= SIZE;
   }

   hashArray[hashIndex] = item;        
}

Lets say if the data we have are string values, how can we implement hashing with it?

As the name echoes, a hash table requires a hash function, ie a function that associates an integer in [0,4] to your key, whatever its type. The hash function should be such that collisions are minimized, so it shouldn't cluster the values.

For character strings, you often use a CRC-like conversion to get an integer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM