uthash.h 哈希表怎么用

写在前面

C语言做算法非常不友好,现在解决的是哈希表问题。

本文不深究uthash.h是如何实现的,仅解释如何使用操作。

详情可以阅读./doc/userguide.txt,里面有非常详细的描述。

软件描述

官网:
https://troydhanson.github.io/uthash/
https://github.com/troydhanson/uthash
CSDN搬运地址

许可:

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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值