1:利用开源
GitHub有针对hash实现的开源代码开源代码,如果不想自己一步步的实现hash的各种操作,可以直接包含开源代码中的头文件uthash.h(内部通过各种宏来实现), 利用里面的接口,来实现hash操作。可以节约大量的时间,并减少自己的代码量。有些时候需要自己进行简易的封装。
2:结构体
typedef struct user_t {
int id;
int cookie;
UT_hash_handle hh;
}user_t;
结构体要自己定义一下
id 表示 key (名字和类型可以修改)
cookie 表示 value(名字和类型可以修改)
UT_hash_handle hh 内部要使用的指针
3:常用函数
添加:HASH_ADD_INT
查找:HASH_FIND_INT
删除:HASH_DEL
4:示例
对调用的接口函数,可以根据自己的需求进行再次封装。
/*******************************************************************************
* @file test1.c
* @verison v1.0.0
* @copyright COPYRIGHT © 2020 CSG
* @author ShiYanKai
* @date: 2021-08-19
* @brief
* @bug
* - 2021-08-19 SYK Created
*******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include "uthash.h"
typedef struct user_t {
int id;
int cookie;
UT_hash_handle hh;
}user_t;
user_t *g_user = NULL;
/*
* 找到hash表中的位置,并返回节点地址
*/
user_t *find_user(int key)
{
user_t *s;
HASH_FIND_INT(g_user, &key, s); //找到key在hash表中的位置,节点地址赋值给s
return s;
}
/*
* 打印表中所有的信息
*/
void print_hash()
{
user_t *user;
for(user = g_user; user != NULL; user = (user_t *)(user->hh.next))
{
printf("user:%d, cookie %d\n", user->id, user->cookie);
}
}
/*
* 删除hash表中节点,参数是节点的地址。调用这个函数时,要获取要删除的节点地址
*/
void delete_hash(user_t *user)
{
HASH_DEL(g_user, user);
free(user);
}
/*
* 向hash表中添加节点
*/
void add_hash(int key, int value)
{
user_t *user;
HASH_FIND_INT(g_user, &key, user);//先检查为key的节点是否已经在hash表中存在,存在就不添加
if (NULL == user)
{
user = (user_t *)malloc(sizeof(user_t));
user->id = key;
user->cookie = value;
HASH_ADD_INT(g_user, id, user);//节点添加到g_user中 这里必须明确告诉插入函数,自己定义的hash结构体中键变量的名字, id:结构体中定义的名字
}
else
{
printf("hash key = %d already\n", key);
}
}
int main()
{
int i;
user_t *user;
user_t *tmp;
for(i = 0; i < 10; i++)
{
add_hash(i, i);
}
printf("\n==========add(0 - 9)=====================\n");
print_hash();
printf("\n==========find 3=====================\n");
tmp = find_user(3);
printf("find 3 ====> user:%d, cookie %d\n", tmp->id, tmp->cookie);
tmp = find_user(5);
delete_hash(tmp);
printf("\n==========del 5=====================\n");
print_hash();
}
显示
yankaishi@zx-dev:~/test/uthash$ ./a.out
==========add(0 - 9)=====================
user:0, cookie 0
user:1, cookie 1
user:2, cookie 4
user:3, cookie 9
user:4, cookie 16
user:5, cookie 25
user:6, cookie 36
user:7, cookie 49
user:8, cookie 64
user:9, cookie 81
==========find 3=====================
find 3 ====> user:3, cookie 9
==========del 5=====================
user:0, cookie 0
user:1, cookie 1
user:2, cookie 4
user:3, cookie 9
user:4, cookie 16
user:6, cookie 36
user:7, cookie 49
user:8, cookie 64
user:9, cookie 81
测试程序:https://download.csdn.net/download/weixin_36209467/21322408