uthash简单使用
在uthash中,哈希表由结构体组成,每个结构体代表一个键值关联。结构体中的一个或多个域构成键(key),结构体自身的指针就是值(value)。
- key 可以是任何数据类型。因为对于 uthash 来说,它只是一个字节序列(a sequence of bytes)。
- 哈希表中,key 必须是唯一的。意味着,在添加元素时必须检查该键是否已经存在。
- 针对不同类型的 key ,使用不同的宏来操作。
/*
* commonly used macros summary here
*/
// int-keyed hash
HASH_ADD_INT(head, intfield, add);
HASH_FIND_INT(head, findint, out);
HASH_REPLACE_INT(head, intfield, add, replaced);
// string-keyed hash (string within structure, i.e. char a[10];)
HASH_ADD_STR(head, strfield, add);
HASH_FIND_STR(head, findstr, out);
HASH_REPLACE_STR(head, strfield, add, replaced);
// string-keyed hash (structure points to string, i.e. char *str;)
HASH_ADD_KEYPTR(hh, head, keyptr, keylen, add);
// ADD, FIND same as above
// pointer-keyed hash (i.e. void *key;)
HASH_ADD_PTR(head, ptrfield, add);
HASH_FIND_PTR(head, findptr, out);
HASH_REPLACE_PTR(head, ptrfield, add, replaced);
// structure-keyed hash
HASH_ADD(hh, head, fieldname, keylen, add);
HASH_FIND(hh, head, keyptr, keylen, out);
HASH_REPLACE(hh, head, fieldname, keylen, add, replaced);
// for all type of key
HASH_COUNT(head);
HASH_ITER(hh, head, el, tmp);
HASH_DEL(head, delptr);
key为int型
定义结构体
#include "uthash.h"
typedef struct my_struct{
int id; /* key */
char name[10];
UT_hash_handle hh; /* make this structure hashalbe */
} Hash;
注意
- 结构体中必须包含 UT_hash_handle。可以任意命名。但如果命名为 hh 则可以使用便利宏(convenience macros)简化添加、查找和删除元素的参数列表。
声明哈希表
Hash *users = NULL; /* important! initialize to NULL */
重要:必须声明为指向定义结构体的空指针(NULL)。
添加
void add_user(int user_id, char *name) {
Hash *find;
HASH_FIND_INT(users, &user_id, find); /* id already in the hash? */
if (find == NULL) {
find = (Hash*)malloc(sizeof(Hash));
find->id = user_id;
HASH_ADD_INT(users, id, find); /* id: name of key field */
}
strcpy(find->name, name);
}
注意:
- 第二个参数为 key 域的名字
- 结构体一经添加到哈