1、使用uthash存储整型
typedef struct {
int id;
int count;
UT_hash_handle hh;
}HashNode;
void HashAdd(HashNode **pTable, int id) {
HashNode *node = malloc(sizeof(HashNode));
memset(node, 0, sizeof(HashNode));
node->id = id;
node->count = 1;
HASH_ADD_INT(*pTable, id, node);
}
void HashDel(HashNode **pTable, HashNode *node) {
HASH_DEL(*pTable, node);
free(node);
}
HashNode *HashFind(HashNode **pTable, int id) {
HashNode *node;
HASH_FIND_INT(*pTable, &id, node);
return node;
}
void HashClear(HashNode **pTable) {
HashNode *node;
HashNode *tmp;
HASH_ITER(hh, *pTable, node, tmp) {
HashDel(pTable, node);
}
}
2、使用uthash存储指针
需要注意的是,在使用 HASH_FIND_PTR 进行哈希查找时,key字段必须是指针的指针
typedef struct {
struct Node *oldNode;
struct Node *newNode;
UT_hash_handle hh; /* makes this structure hashable */
} HashNode;
void HashAdd(HashNode **pHashTable, HashNode *node) {
HASH_ADD_PTR(*pHashTable, oldNode, node);
}
void HashDel(HashNode **pHashTable, HashNode *node) {
HASH_DEL(*pHashTable, node);
}
HashNode *HashFind(HashNode **pHashTable, struct Node *oldNode) {
HashNode *s;
HASH_FIND_PTR(*pHashTable, &oldNode, s);
return s;
}
void HashClear(HashNode **pHashTable) {
HASH_CLEAR(hh, *pHashTable);
}
void HashCount(HashNode **pHashTable) {
HASH_COUNT(hh, *pHashTable);
}
void ForEachProcess(HashNode **pHashTable) {
HashNode *node = NULL;
HashNode *tmp = NULL;
HASH_ITER(hh, *pHashTable, node, tmp) {
struct Node *newNode = node->newNode;
struct Node **oldNeighbors = newNode->neighbors;
/* 其他处理 */
}
}
int KeyCmp(HashNode * a, HashNode * b)
{
if (a->oldNode == b->oldNode) {
return 0;
}
return (a->oldNode > b->oldNode) ? 1 : 0;
}
void HashSort(HashNode **pHashTable)
{
HASH_SORT(pHashTable, KeyCmp);
}
3、使用uthash存储字符串
typedef struct {
char word[12]; /* we'll use this field as the key */
int count;
int forbid;
UT_hash_handle hh; /* makes this structure hashable */
}HashNode;
void HashAdd(HashNode **pHashTable, HashNode *s) {
/*
如果pHashTable中存储的是字符串指针的话,需要用
HASH_ADD_KEYPTR(待尝试))
*/
HASH_ADD_STR(*pHashTable, word, s);
}
void HashDel(HashNode **pHashTable, HashNode *s) {
HASH_DEL(*pHashTable, s);
free(s);
}
HashNode *HashFind(HashNode **pHashTable, char *word) {
struct hash_entry *s;
HASH_FIND_STR(*pHashTable, word, s);
return s;
}
4、可以不使用上面提供的方法,直接只用原始宏进行处理
#define HASH_ADD(hh,head/*头指针*/,fieldname/*key字段名字*/,keylen_in/*key字段长度*/,add)/*要加入的指针*/
#define HASH_DELETE(hh,head,delptr)
#define HASH_FIND(hh,head,keyptr,keylen,out)
#define HASH_ITER(hh,head,el,tmp)
#define HASH_CNT(hh,head)
#define HASH_CLEAR(hh,head) /*插入的元素需要自己删除*/