uthash使用方法
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;
}