struct my_struct{
int id; /* key */
int val;
UT_hash_handle hh; /* makes this structure hashable */
};
struct my_struct *users = NULL;
直接添加元素
/* Add item */
void add_user(int user_id, int user_val){
struct my_struct *s;
s = (struct my_struct *)malloc(sizeof(struct my_struct));
s->id = user_id;
s->val = user_val;
HASH_ADD_INT(users, id, s);
}
先检查哈希表中是否存在该元素
/* Add an item to a hash */
void add_user(int user_id, int user_val){
struct my_struct *s;
HASH_FIND_INT(users, &user_id, s); /* id already in the hash? */
if(s==NULL){
s = (struct my_struct *)malloc(sizeof(struct my_struct));
s->id = user_id;
HASH_ADD_INT(users, id, s);
}
s->val = user_val;
}
/* Find a structure using its key */
struct my_struct *find_user(int user_id){
struct my_struct *s;
HASH_FIND_INT(users, &user_id, s); /* s: output pointer */
return s;
}
/* Delete an item from a hash */
void delete_user(struct my_struct *user){
HASH_DEL(users, user); /*user: pointer to delete */
free(user); /* optional */
}
/* Delete all items from a hash */
void delete_all(){
struct my_struct *current_user, *tmp;
HASH_ITER(hh, users, current_user, tmp){
HASH_DEL(users, current_user); /* delete; users advances to next */
free(current_user); /* optional - if you want to free */
}
}
/* All-at-once deletion */
HASH_CLEAR(hh, users);