C语言利用uthash.h实现hashmap

下载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);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值