汇总:
参考:http://troydhanson.github.io/uthash/userguide.html
一、键值是INT型
1、定义结构体,对应键值是整形int,需要有个全局指针比如users
typedef struct {
int id; /* key */
char name[10];
int cnt;
UT_hash_handle hh; /* makes this structure hashable */
}my_struct;
my_struct *users = NULL; /* important! initialize to NULL */
2、ADD&查找操作
先HASH_FIND_INT,如果不能找到,那么新加到HASH_ADD_INT中;如果能找到,就对cnt++;
注意HASH_FIND_INT的第二个入参是当前键值的名称
void add_user(int user_id, char *name, int cnt) {
my_struct *s;
HASH_FIND_INT(users, &user_id, s); /* id already in the hash? */
if (s == NULL) {
s = (my_struct *)malloc(sizeof *s);
s->id = user_id;
s->cnt = cnt;
strcpy(s->name, name);
HASH_ADD_INT(users, id, s); /* id: name of key field */
} else {
s->cnt += cnt;
}
}
3、这个遍历操作比较新鲜;next是s->hh.next
void print_users() {
my_struct *s;
for (s = users; s != NULL; s = s