UTHash在数据管理中应用广泛,现给出使用范例以供参考:
#include <uthash.h> // 包含头文件
//1、hash
typedef struct myhash {
int key;
int cnt;
UT_hash_handle hh;
} MyHash;
MyHash *g_myHash = NULL;
// 查找、插入
void HashFind(int key)
{
MyHash *temp = NULL;
HASH_FIND_INT(g_myHash, &key, temp);
if (temp == NULL) {
temp = (MyHash *)malloc(sizeof(MyHash));
temp->key = key;
temp->cnt = 1;
HASH_ADD_INT(g_myHash, key, temp);
} else {
temp->cnt++;
}
}
// 遍历
void HashFor()
{
MyHash *newTemp = NULL;
MyHash *temp = NULL;
HASH_ITER(hh, g_myHash, newTemp, temp) {
printf("%d %d,", newTemp->key, newTemp->cnt);
}
for (MyHash *p = g_myHash; p != NULL; p = (MyHash *)p->hh.next) { // 向后遍历
}
for (MyHash *p = g_myHash; p != NULL; p = (MyHash *)p->hh.prev) { // 向前遍历
}
}
void HashFree()
{
MyHash *newTemp = NULL;
MyHash *temp = NULL;
HASH_ITER(hh, g_myHash, newTemp, temp) {
HASH_DEL(g_myHash, newTemp);
free(newTemp);
newTemp = NULL;
}
}
typedef struct {
int a;
int b;
} KeyStr;
typedef struct {
KeyStr key; // key是结构体
UT_hash_handle hh;
} HashStr;
int findPairs(int* nums, int numsSize, int k)
{
HashStr *hashTbl = NULL;
int ret = 0;
for (int i = 0; i < numsSize - 1; i++) {
for (int j = i + 1; j < numsSize; j++) {
if (abs(nums[j] - nums[i]) != k) {
continue;
}
HashStr *temp = NULL;
KeyStr key;
memset(&key, 0, sizeof(KeyStr));
key.a = nums[i];
key.b = nums[j];
HASH_FIND(hh, hashTbl, &key, sizeof(KeyStr), temp);
if (temp) {
continue;
}
temp = (HashStr *)malloc(sizeof(HashStr));
temp->key.a = key.a;
temp->key.b = key.b;
HASH_ADD(hh, hashTbl, key, sizeof(KeyStr), temp);
if (nums[i] == nums[j]) {
ret++;
continue;
}
KeyStr key1;
memset(&key1, 0, sizeof(KeyStr));
key1.a = nums[j];
key1.b = nums[i];
HashStr *p = NULL;
HASH_FIND(hh, hashTbl, &key1, sizeof(KeyStr), p);
if (p == NULL) {
p = (HashStr *)malloc(sizeof(HashStr));
p->key.a = key1.a;
p->key.b = key1.b;
HASH_ADD(hh, hashTbl, key, sizeof(KeyStr), p);
ret++;
}
}
}
HashStr *q1 = NULL, *q2 = NULL;
HASH_ITER(hh, hashTbl, q1, q2) {
printf("%d %d\n", q1->key.a, q1->key.b);
}
return ret;
}
int CompCnt(MyHash *a, MyHash *b)
{
return a->cnt - b->cnt; // 升序排列
}
// 排序
void HashSort()
{
HASH_SORT(g_myHash, CompCnt);
}
// 获取hash表中元素个数
int HashGetCnt()
{
int cnt = HASH_COUNT(g_myHash);
return cnt;
}