写在前面
C语言做算法非常不友好,现在解决的是哈希表问题。
本文不深究uthash.h是如何实现的,仅解释如何使用操作。
详情可以阅读./doc/userguide.txt,里面有非常详细的描述。
软件描述
官网:
https://troydhanson.github.io/uthash/
https://github.com/troydhanson/uthash
优快云搬运地址
许可:
BSD reserved (@Version: 2.3.0)
使用说明:
https://troydhanson.github.io/uthash/userguide.html
类型
STR 字符串类型
INT 整数类型
PTR 指针类型
使用方法
定义一个哈希结构体
结构体格式没有特别要求,需要注意的是,一定要有 UT_hash_handle hh 元素,它是uthash能运转的基础,有兴趣的同学可以自行查看其定义。
typedef struct hashInt {
int key; // 依据哈希表的类型来决定
int val; // 自定义,可有可无
UT_hash_handle hh;
} MyHashInt;
定义一个头头
后面的表全部靠这头头作为起始,可以理解成它是原本我们定义hashTable[]的指针。
MyHashInt *hashHead = NULL;
ut hash int
整数类型
定义结构体
typedef struct hashInt {
int key; // 记录索引
int val; // 记录数字出现的次数
UT_hash_handle hh;
} MyHashInt;
HASH_FIND_INT
原型:HASH_FIND_INT(head,findint,out)
head - (struct xx)头头
findint - (int)指向需要查找的int的指针
out - (struct xx)find结果的输出地址,如果为空即未找到
HASH_ADD_INT
原型:HASH_ADD_INT(head,intfield,add)
head - (struct xx)头头
intfield - 结构体定义的int名称
add - (struct xx)add结构体的内存地址,记得使用malloc并判断返回值。
HASH_REPLACE_INT
原型:HASH_REPLACE_INT(head,intfield,add,replaced)
HASH_DEL
原型:HASH_DEL(head,delptr)
// demo
#define PRT(fmt, ...) printf("%s:%d -- " fmt, __FILE__, __LINE__, ##__VA_ARGS__)
#define PRT_N(fmt, ...) printf(fmt, ##__VA_ARGS__)
void UTHash_IntTest(void)
{
typedef struct hashInt {
int key;
int count;
UT_hash_handle hh;
} MyHashInt;
MyHashInt *hashIntHead = NULL;
for (int i = 0; i < 20; i++) {
int randInt = (int)(rand() % 10);
PRT("Round%3d, key:%3d, ", i, randInt);
MyHashInt *tInt = NULL;
HASH_FIND_INT(hashIntHead, &randInt, tInt);
if (tInt != NULL) {
tInt->count++;
PRT_N("value:%3d, found\n", tInt->count);
continue;
}
tInt = (MyHashInt *)malloc(sizeof(MyHashInt));
if (tInt == NULL) {
PRT("malloc error\n");
return -1;
}
tInt->key = randInt;
tInt->count = 1;
PRT_N("value: 1, new\n");
HASH_ADD_INT(hashIntHead, key, tInt);
}
}
to be continue