【发布时间】:2020-11-22 10:53:49
【问题描述】:
我必须创建一个 HashMap。我创建了两个结构。一个node struct 和一个table struct。第二个结构将“包含”我的节点。我的麻烦是insert 函数:我必须在我的表(*t)中插入一对(键,值)。问题是键和值类型必须是通用的。所以,我想插入 int, double, char, ecc.. 我怎样才能把我的函数变成一个泛型函数?
插入.c
struct node{
int key;
int val;
struct node *next;
struct node *prev;
};
struct table{
int size;
struct node **list;
};
int hashCode(int key){
if(key>0)
return key-1;
return key+1;
}
void insert(struct table *t,int key,int val){
int pos = hashCode(key);
struct node *list = t->list[pos];
struct node *newNode = (struct node*)malloc(sizeof(struct node));
struct node *temp = list;
while(temp){
if(temp->key==key){
printf("%s", "Key already created");
return;
}
temp = temp->next;
}
newNode->next = list;
newNode->key = key;
newNode->val = val;
if(list!=NULL){
list->prev = newNode;
}
t->list[pos] = newNode;
newNode->prev = NULL;
}
main.c
int main(){
struct table *t = /* I create the structure */ ;
insert(t,2,3);
insert(t,3,4);
insert(t,2,3);
// insert(t,'a','c'); function insert should execute also with char, int, float, double ecc...
return 0;
}
【问题讨论】:
-
您可以使用
union存储键和值,并使用enum建议存储哪些数据。 -
我从未使用过 union 和 enum,如何在我的函数中使用它们? @jha-G
-
您可以创建一个通用哈希实现,该实现为键提供比较函数,并将键存储为 void 数据类型(或指向 void 的指针)。
-
Insert 参数是 Int,那么我该如何传递一个 char 呢?我需要传递所有 type ,而不仅仅是 int 。 @PaulOgilvie
-
您也可以使用
void *来表示key和value,并在您的node中添加一个额外的参数type(可以使用enum)来解码以纠正需要时输入
标签: c generics struct insert hashmap