1 uthash 简介
uthash 哈希的实现很简单,它不是一个库,只是一个头文件,使用的时候incluede进去就行了
#include "uthash.h"
关于 uthash 的官方文档 :
https://troydhanson.github.io/uthash/userguide.html#_a_hash_in_c
下载头文件源码:
GitHub - troydhanson/uthash: C macros for hash tables and more
uthash 支持哈希表的如下操作:
-
add/replace
-
find
-
delete
-
count
-
iterate
-
sort
2 uthash 的使用
2.1 创建自己的哈希结构
以定义一个 学生信息为例,使用学号id 当做哈希表中的key,这个key是唯一的,类型也可以是任意的类型,这里根据需要定义为int类型,name也是根据需要自定义的,也可以是其它类型的,也可以不定义。
#include "uthash.h"
struct my_struct {
int id; /* key , unique , can be any type, char/pointer,etc */
char name[10]; /* can not use */
UT_hash_handle hh; /* makes this structure hashable */
};
2.2 声明哈希表
注意,这个声明一个全局变量,哈希表的头,一定要初始化为NULL
struct my_struct *users = NULL; /* important! initialize to NULL */
如果不想定义全局变量,想要以参数的形式,需要注意,一定要使用二重指针,不然是不正确的。
这部分官方文档有说明:
/* bad */
void add_user(struct my_struct *users, int user_id, char *name) {
...
HASH_ADD_INT(users, id, s);
}
/* good */
void add_user(struct my_struct **users, int user_id, char *name) { ...
...
HASH_ADD_INT(*users, id, s);
}
2.3 哈希表中 add item
如果key是 int 类型, HASH_ADD