如果索引不是整数,我们如何在 C++ 中插入哈希表

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

本文关键字:C++ 哈希表 插入 我们 索引 整数 如果      更新时间:2023-10-16

如果我有 4 个数据,如 1,2,3,4,并且哈希表大小为 5,那么我们可以根据索引插入它,并使用如下所示的哈希函数根据索引搜索项目。

h(x)= x%5

插入功能:

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;        
}

假设我们拥有的数据是字符串值,我们如何用它实现哈希?

顾名思义,哈希表需要一个哈希函数,即将 [0,4] 中的整数与您的键相关联的函数,无论其类型如何。哈希函数应使冲突最小化,因此不应对值进行聚类。

对于字符串,通常使用类似 CRC 的转换来获取整数。