下载uthash.h
【官网下载】:官网下载
下载zip后,找到src目录,将其复制到C语言的头文件夹中。
如果使用的是vs:
1.随便打开一个c语言的文件,ctrl+鼠标正建打开头文件。
2.
打开文件夹后,复制进去,重启vs即可。
使用
定义结构体
typedef struct my_map{
int key;
int value;
UT_hash_handle hh; // make this structure hashable
}map;
//结构体中的key与value的类型可以根据情况自己定义
map* hashMap = NULL;
添加元素
void hashMapAdd(int key,int value) {
map* s;
HASH_FIND_INT(hashMap, &key, s);
if (s == NULL) {
s = (map*)malloc(sizeof(map));
s->key = key;
HASH_ADD_INT(hashMap, key, s);
}
s->value = value;
}
HASH_FIND_INT(hashMap, &key, s);
hashmap:从哪里查找,传入指针
key:查找的元素,传入指针
s:out,结构存放,指针
HASH_ADD_INT(hashMap, key, s);
hashmap:添加到哪里,传入指针
key:添加的元素
s:要添加的结构指针
HASH_ADD_INT表示添加的键值为int类型
HASH_ADD_STR表示添加的键值为字符串类型
HASH_ADD_PTR表示添加的键值为指针类型
HASH_ADD表示添加的键值可以是任意类型
查找
int hashMapFind(int key) {
map* s;
s = (map*)malloc(sizeof(map));
HASH_FIND_INT(hashMap, &key, s);
return s->value;
}
删除
void hashMapDelete(int key) {
map* s;
HASH_FIND_INT(hashMap, &key, s);
if (s != NULL) {
HASH_DEL(hashMap, s);
}
}
清除
void hashMapClean() {
map* current, * tmp;
HASH_ITER(hh, hashMap, current, tmp) {
HASH_DEL(hashMap, current);
free(current);
}
}
遍历
void Traverse() {
map* s;
for (s = hashMap; s != NULL; s = s->hh.next) {
printf("key: % d, value : % d\n", s->key, s->value);
}
}
全部代码
#include<uthash.h>
typedef struct my_map{
int key;
int value;
UT_hash_handle hh; // make this structure hashable
}map;
map* hashMap = NULL;
void hashMapAdd(int key,int value) {
map* s;
HASH_FIND_INT(hashMap, &key, s);
if (s == NULL) {
s = (map*)malloc(sizeof(map));
s->key = key;
HASH_ADD_INT(hashMap, key, s);
}
s->value = value;
}
int hashMapFind(int key) {
map* s;
s = (map*)malloc(sizeof(map));
HASH_FIND_INT(hashMap, &key, s);
return s->value;
}
void hashMapDelete(int key) {
map* s;
HASH_FIND_INT(hashMap, &key, s);
if (s != NULL) {
HASH_DEL(hashMap, s);
}
}
void hashMapClean() {
map* current, * tmp;
HASH_ITER(hh, hashMap, current, tmp) {
HASH_DEL(hashMap, current);
free(current);
}
}
void Traverse() {
map* s;
for (s = hashMap; s != NULL; s = s->hh.next) {
printf("key: % d, value : % d\n", s->key, s->value);
}
}