uthash哈希的使用
发布日期:2021-06-29 04:13:00
浏览次数:2
分类:技术文章
本文共 1731 字,大约阅读时间需要 5 分钟。
做项目遇到需要使用到键值对的,一般我们会优先考虑map,multimap。
最近在看cocos2d-x源码,发现了一个更高效的用法uthash
头文件uthash.h在cocos2dx\support\data_support\下可以找到
下面是一个简单的使用:
#include "uthash.h"#include#include /*这个uthash必须构造一个结构体*/struct packet{ int key; /*这个是用来做hash的key值*/ char msg[10]; UT_hash_handle hh; /*这个结构是uthash的结构体,里面包含next,prev,hash值等信息*/};int main(){ struct packet *pkt, *tmp; int i; struct packet *hash_packet = NULL; /*必须初始化为NULL*/ /*打印这个hash的节点数*/ printf ("hash count = %d \n", HASH_COUNT(hash_packet)); /*往hash中添加节点*/ for (i=0; i<10; i++) { pkt = (struct packet *)malloc(sizeof(struct packet)); pkt->key = i; sprintf (pkt->msg, "i=%d", i); HASH_FIND_INT(hash_packet, &i, tmp); if (tmp != NULL) { printf ("The key(%d) exists in hash. \n", i); continue; } HASH_ADD_INT(hash_packet, key, pkt); printf ("insert item. key=%d,value=%p \n", i, pkt); } printf ("hash count = %d \n", HASH_COUNT(hash_packet)); /*通过key查找*/ for (i=0; i<13; i++) { HASH_FIND_INT(hash_packet, &i, tmp); if (tmp == NULL) { printf ("find not item. key=%d,value=%p \n", i, tmp); continue; } printf ("find item. key=%d,value=%p \n", i, tmp); } printf ("hash count = %d \n", HASH_COUNT(hash_packet)); /*遍历这个hash表*/ struct packet* mytemp = NULL; for (mytemp = hash_packet; mytemp != NULL; mytemp = (packet*)mytemp->hh.next) printf (" %d => %s \n", mytemp->key, mytemp->msg); /*删除节点*/ for (i=0; i<13; i++) { HASH_FIND_INT(hash_packet, &i, tmp); if (tmp == NULL) { printf ("find not item. key=%d,value=%p \n", i, tmp); continue; } /*删除节点不会释放你的空间必须自己释放*/ HASH_DEL(hash_packet, tmp); free(tmp); printf ("delete itme. key=%d,value=%p \n", i, tmp); } printf ("hash count = %d \n", HASH_COUNT(hash_packet)); system("pause"); return 0;}
转载地址:https://blog.csdn.net/zh634455283/article/details/17552713 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
感谢大佬
[***.8.128.20]2024年04月02日 18时57分42秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
全局异常处理之自定义全局错误页面、404及500错误页面
2019-04-29
全局异常处理之@ControllerAdvice+@ExceptionHandler
2019-04-29
全局异常处理之SimpleMappingExceptionResolver
2019-04-29
全局异常处理之如何使用HandlerExceptionResolver接口
2019-04-29
【Neuralink 与大脑的神奇未来】Part 2:大脑
2019-04-29
【Neuralink 与大脑的神奇未来】Part 3:脑机接口
2019-04-29
【Neuralink 与大脑的神奇未来】Part 4:Neuralink 的挑战
2019-04-29
【Neuralink 与大脑的神奇未来】Part 5:巫师时代
2019-04-29
【Neuralink与大脑的神奇未来】Part 6:大融合
2019-04-29
人工智能革命(上):通往超级智能之路
2019-04-29
人工智能革命(下):永生还是毁灭
2019-04-29
解密小米生态链:从构建到定义产品
2019-04-29
张一鸣的流量生意
2019-04-29
重新定义马桶
2019-04-29
从移动互联网困局漫谈人工智能的未来
2019-04-29
如何设计一款让用户“上瘾”的产品?
2019-04-29
墙裂推荐几款桌面应用
2019-04-29
如何避免掉进心理陷阱?
2019-04-29
从价值观选择到重构思维模型
2019-04-29