c语言 开源hash项目 —— uthash


 1 //------------------------------------------
 2 //      c语言 开源hash项目 —— uthash 
 3 //
 4 //
 5 //eg: 对 字符串进行查找和删除 字符指针
 6 //   
 7 //    warning: uthash 对  字符指针和字符数组,
 8 //                        插入的函数是不一样的,查找的函数是一致的
 9 //        对所有的类型,删除的操作
10 //-------------------------------------------
11 
12 #include "gtest/gtest.h"
13 #include <iostream>
14 using namespace std;
15 
16 #include"uthash/uthash.h" 
17 
18 typedef struct {
19     int ikey;                    /* key */
20     char value[10];
21     UT_hash_handle hh;
22 }uthash_int;
23 
24 // 查找
25 uthash_int *find_uthash_int(uthash_int *g_users, int ikey)
26 {
27     uthash_int *s = NULL;
28     HASH_FIND_INT(g_users, &ikey, s);        // find int 
29     return s;
30 }
31 
32 // 插入
33 void add_uthash_int(uthash_int *g_users, int ikey, char *value_buf)
34 {
35     uthash_int *s = NULL;
36     HASH_FIND_INT(g_users, &ikey, s);  /* 插入前先查看key值是否已经在hash表g_users里面了 */
37     if (s == NULL) {
38         s = (uthash_int*)malloc(sizeof(uthash_int));
39         s->ikey = ikey;
40         HASH_ADD_INT(g_users, ikey, s);  /* 这里必须明确告诉插入函数,自己定义的hash结构体中键变量的名字 */
41     }
42     strcpy(s->value, value_buf);
43 }
44 
45 // 删除
46 void delete_uthash_int(uthash_int *g_users, int ikey)
47 {
48     uthash_int *s = NULL;
49     HASH_FIND_INT(g_users, &ikey, s);
50     if (s == NULL) {
51         HASH_DEL(g_users, s); 
52         free(s);
53     }
54 }
55 
56 // clear 
57 void clear_uthash_int(uthash_int *g_users)
58 {
59     uthash_int *current_user = NULL;
60     uthash_int *tmp = NULL;
61     HASH_ITER(hh, g_users, current_user, tmp) {
62         HASH_DEL(g_users, current_user);
63         free(current_user);
64     }
65 }
66 
67 TEST(test, test_01)
68 {
69 
70 }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM