c - 有两个哈希表,当删除一个项目时,它会删除另一个
问题描述
我实现了一个哈希表,并像这样初始化了两个不同的哈希表:
hashtable *active_users = create();
hashtable *inactive_users = create();
上面哈希表的一个元素如下所示:
typedef struct user{
char nick[6];
char name[26];
int n_messages;
bool occupied;
}user;
在我的主程序中,我有一个函数可以删除用户active_users
并将其插入其中inactive_users
,问题是当从 中删除项目active_users
后,将其插入其中后inactive_users
,出于某种原因将其删除。
hashtable * delete_user(hashtable *active_users, hashtable *inactive_users, char *input_a){
if(contains(active_users, input_a) != -1){
user *tmp = get_item(active_users, input_a); //gets the user from the active_users hashtable
if(load_factor(inactive_users)) //checks the hashtable size
inactive_users = resize_HashTable(inactive_users); // if needed it resizes
insert2(inactive_users, tmp); //insert in inactive_users
print_table(inactive_users);
printf("\n");
delete_item(active_users, input_a); //deletes from active_users
print_table(inactive_users);
printf("+ user %s removed\n", input_a);
}else{
printf("+ user %s doesnt exist\n", input_a);
}
return inactive_users;
}
inactive_users
在上面的代码中,我在插入新用户并从其中删除同一用户后打印了哈希表,active_users
以便您可以看到问题。
inactive_users
插入后:
i: 0, nick: me, name: mig
i: 1, nick: -, name: -
i: 2, nick: -, name: -
i: 3, nick: -, name: -
i: 4, nick: -, name: -
inactive_users
从删除后active_users
i: 0, nick: -, name: -
i: 1, nick: -, name: -
i: 2, nick: -, name: -
i: 3, nick: -, name: -
i: 4, nick: -, name: -
要从哈希表中删除一个项目,我只需将其变量“占用”标记为 false,这意味着该点现在可以自由用于插入。编码:
void delete_item(hashtable *HashTable, char *nick){
int position = contains(HashTable, nick);
if(position != -1){
HashTable[position].buckets->occupied = false;
HashTable->elements--;
}
}
解决方案
occupied
是结构的一个字段,您在..user
上设置为 falsedelete_item
相反,您应该将存储桶设置为 null
void delete_item(hashtable *HashTable, char *nick){
int position = contains(HashTable, nick);
if(position != -1){
HashTable[position].buckets = null;
HashTable->elements--;
}
}
推荐阅读
- c# - 如何在使用 .NET Core 的控制台应用程序中从 appsettings.json 获取值?
- javascript - Jqgrid 中 colNames <> colModel 错误的长度
- ssis - 包作为孩子运行,但作为孙子失败
- node.js - 对象作为属性 mongoose mongodb
- javascript - 编辑电子邮件firestore vue
- python - 如何使用 Anaconda 管理具有虚拟环境的库?
- python - 如何按值对python中的列表进行分类?
- jenkins - 将 Jenkins 流水线构建作业阶段显示为失败,而不会使整个作业失败
- java - 对于 Java Swing,如何访问 (x,y) 处的元素?
- c - 计算C中列表中的不同元素