工科生一枚,热衷于底层技术开发,有强烈的好奇心,感兴趣内容包括单片机,嵌入式Linux,Uboot等,欢迎学习交流!
爱好跑步,打篮球,睡觉。
欢迎加我QQ1500836631(备注CSDN),一起学习交流问题,分享各种学习资料,电子书籍,学习视频等。
uthash简介
由于C语言本身不存在哈希,但是当需要使用哈希表的时候自己构建哈希会异常复杂。因此,我们可以调用开源的第三方头文件,这只是一个头文件:uthash.h。我们需要做的就是将头文件复制到您的项目中,然后:#include “uthash.h”。由于uthash仅是头文件,因此没有可链接的库代码。
使用uthash添加,查找和删除通常是常数时间的操作,此哈希的目标是简约高效。它大约有1000行C。它会自动内联,因为它是作为宏实现的。
uthash还包括三个额外的头文件,主要提供链表,动态数组和字符串。utlist.h为C结构提供了链接列表宏。utarray.h使用宏实现动态数组。utstring.h实现基本的动态字符串。
github下载链接:https://github.com/troydhanson/uthash
uthash的使用
定义结构体
这里我们将id作为一个索引值,也就是键值,将name作为value。
1#include "uthash.h" 2struct my_struct { 3 int id; /* key */ 4 char name[10]; 5 UT_hash_handle hh; /* makes this structure hashable */ 6}; 7/*声明哈希为NULL指针*/ 8struct my_struct *users = NULL; /* important! initialize to NULL */
注意:一定要包含UT_hash_handle hh;hh不需要初始化。它可以命名为任何名称,但是我们一般都命名为hh。
添加
HASH_ADD_INT表示添加的键值为int类型
HASH_ADD_STR表示添加的键值为字符串类型
HASH_ADD_PTR表示添加的键值为指针类型
HASH_ADD表示添加的键值可以是任意类型
1void add_user(int user_id, char *name) { 2 struct my_struct *s; 3 /*重复性检查,当把两个相同key值的结构体添加到哈希表中时会报错*/ 4 HASH_FIND_INT(users, &user_id, s); /* id already in the hash? */ 5 /*只有在哈希中不存在ID的情况下,我们才创建该项目并将其添加。否则,我们只修改已经存在的结构。*/ 6 if (s==NULL) { 7 s = (struct my_struct *)malloc(sizeof *s); 8 s->id = user_id; 9 HASH_ADD_INT( users, id, s ); /* id: name of key field */ 10 } 11 strcpy(s->name, name); 12}
HASH_ADD_INT函数中,第一个参数users是哈希表,第二个参数id是键字段的名称。最后一个参数s是指向要添加的结构的指针。
查找
1struct my_struct *find_user(int user_id) { 2 struct my_struct *s; 3 HASH_FIND_INT( users, &user_id, s ); /* s: output pointer */ 4 return s; 5}
在上述代码中,第一个参数users是哈希表,第二个参数是user_id的地址(一定要传递地址)。最后s是输出变量。当可以在哈希表中找到相应键值时,s返回给定键的结构,当找不到时s返回NULL。
替换
HASH_REPLACE宏等效于HASH_ADD宏,HASH_REPLACE会尝试查找和删除项目外。如果找到并删除了一个项目,它还将返回该项目的指针作为输出参数。
1void replace_user(HashHead *head, HashNode *newNode) { 2 HashNode *oldNode = find_user(*head, newNode->id); 3 if (oldNode) 4 HASH_REPLACE_INT(*head, id, newNode, oldNode); 5}
删除
要从哈希表中删除结构,必须具有指向它的指针。(如果只有键,请先执行HASH_FIND以获取结构指针)。
1void delete_user(struct my_struct *user) { 2 HASH_DEL(users, user); /* user: pointer to deletee */ 3 free(user); /* optional; it's up to you! */ 4}
同样,这里users是哈希表,user是指向我们要从哈希中删除的结构的指针。
删除结构只是将其从哈希表中删除,并非free 。何时释放结构的选择完全取决于自己;uthash永远不会释放您的结构
循环删除
HASH_ITER是一个宏定义,程序执行时被替换为一个循环。
1void delete_all() { 2 struct my_struct *current_user, *tmp; 3 4 HASH_ITER(hh, users, current_user, tmp) { 5 HASH_DEL(users,current_user); /* delete; users advances to next */ 6 free(current_user); /* optional- if you want to free */ 7 } 8}
删除哈希表所有元素
如果您只想删除所有项目,但不释放它们或进行每个元素的清理,则可以通过一次操作更有效地做到这一点:
HASH_CLEAR(hh,users);
之后,列表头(此处为users)将设置为NULL。
计算哈希表元素个数
1unsigned int num_users; 2num_users = HASH_COUNT(users); 3printf("there are %u users\n", num_users);
当users为NULL时,HASH_COUNT会返回0.
遍历哈希表中的所有项目
1void print_users() { 2 struct my_struct *s; 3 4 for(s=users; s != NULL; s=s->hh.next) { 5 printf("user id %d: name %s\n", s->id, s->name); 6 } 7}
还有一个hh.prev指针,可用于从任何已知项开始向后迭代哈希。
由于hh.prev和hh.next字段的缘故,可以在哈希中向前和向后迭代。可以通过重复跟随这些指针来访问哈希中的所有项目,因此哈希也是双链表。
排序哈希表
HASH_SORT( users, name_sort );
第二个参数是指向比较函数的指针。它必须接受两个指针参数(要比较的项目),并且如果第一个项目分别在第二个项目之前,等于或之后排序,则必须返回小于零,零或大于零的int。 (这与标准C库中的strcmp或qsort使用的约定相同)。
1int sort_function(void *a, void *b) { 2 /* compare a to b (cast a and b appropriately) 3 * return (int) -1 if (a < b) 4 * return (int) 0 if (a == b) 5 * return (int) 1 if (a > b) 6 */ 7}
name_sort和id_sort的两个排序函数示例。
1int name_sort(struct my_struct *a, struct my_struct *b) { 2 return strcmp(a->name,b->name); 3} 4 5int id_sort(struct my_struct *a, struct my_struct *b) { 6 return (a->id - b->id); 7} 8 9void sort_by_name() { 10 HASH_SORT(users, name_sort); 11} 12 13void sort_by_id() { 14 HASH_SORT(users, id_sort); 15}
完整代码
1#include <stdio.h> /* gets */ 2#include <stdlib.h> /* atoi, malloc */ 3#include <string.h> /* strcpy */ 4#include "uthash.h" 5 6struct my_struct { 7 int id; /* key */ 8 char name[10]; 9 UT_hash_handle hh; /* makes this structure hashable */ 10}; 11 12struct my_struct *users = NULL; 13 14void add_user(int user_id, char *name) { 15 struct my_struct *s; 16 17 HASH_FIND_INT(users, &user_id, s); /* id already in the hash? */ 18 if (s==NULL) { 19 s = (struct my_struct *)malloc(sizeof *s); 20 s->id = user_id; 21 HASH_ADD_INT( users, id, s ); /* id: name of key field */ 22 } 23 strcpy(s->name, name); 24} 25 26struct my_struct *find_user(int user_id) { 27 struct my_struct *s; 28 29 HASH_FIND_INT( users, &user_id, s ); /* s: output pointer */ 30 return s; 31} 32 33void delete_user(struct my_struct *user) { 34 HASH_DEL(users, user); /* user: pointer to deletee */ 35 free(user); 36} 37 38void delete_all() { 39 struct my_struct *current_user, *tmp; 40 41 HASH_ITER(hh, users, current_user, tmp) { 42 HASH_DEL(users, current_user); /* delete it (users advances to next) */ 43 free(current_user); /* free it */ 44 } 45} 46 47void print_users() { 48 struct my_struct *s; 49 50 for(s=users; s != NULL; s=(struct my_struct*)(s->hh.next)) { 51 printf("user id %d: name %s\n", s->id, s->name); 52 } 53} 54 55int name_sort(struct my_struct *a, struct my_struct *b) { 56 return strcmp(a->name,b->name); 57} 58 59int id_sort(struct my_struct *a, struct my_struct *b) { 60 return (a->id - b->id); 61} 62 63void sort_by_name() { 64 HASH_SORT(users, name_sort); 65} 66 67void sort_by_id() { 68 HASH_SORT(users, id_sort); 69} 70 71int main(int argc, char *argv[]) { 72 char in[10]; 73 int id=1, running=1; 74 struct my_struct *s; 75 unsigned num_users; 76 77 while (running) { 78 printf(" 1. add user\n"); 79 printf(" 2. add/rename user by id\n"); 80 printf(" 3. find user\n"); 81 printf(" 4. delete user\n"); 82 printf(" 5. delete all users\n"); 83 printf(" 6. sort items by name\n"); 84 printf(" 7. sort items by id\n"); 85 printf(" 8. print users\n"); 86 printf(" 9. count users\n"); 87 printf("10. quit\n"); 88 gets(in); 89 switch(atoi(in)) { 90 case 1: 91 printf("name?\n"); 92 add_user(id++, gets(in)); 93 break; 94 case 2: 95 printf("id?\n"); 96 gets(in); id = atoi(in); 97 printf("name?\n"); 98 add_user(id, gets(in)); 99 break; 100 case 3: 101 printf("id?\n"); 102 s = find_user(atoi(gets(in))); 103 printf("user: %s\n", s ? s->name : "unknown"); 104 break; 105 case 4: 106 printf("id?\n"); 107 s = find_user(atoi(gets(in))); 108 if (s) delete_user(s); 109 else printf("id unknown\n"); 110 break; 111 case 5: 112 delete_all(); 113 break; 114 case 6: 115 sort_by_name(); 116 break; 117 case 7: 118 sort_by_id(); 119 break; 120 case 8: 121 print_users(); 122 break; 123 case 9: 124 num_users=HASH_COUNT(users); 125 printf("there are %u users\n", num_users); 126 break; 127 case 10: 128 running=0; 129 break; 130 } 131 } 132 133 delete_all(); /* free any structures */ 134 return 0; 135}
键值的各种类型举例
整型键值
当键值为整型时,可以使用HASH_ADD_INT和HASH_FIND_INT。(对于所有类型的键,其他操作(例如HASH_DELETE和)HASH_SORT都是相同的)。
字符串键值
当键值为字符串时,具体要使用那个函数取决于结构体中的键值为字符串数组还是字符串指针。 这一点很重要。当结构体中的键值为字符串数组时,使用HASH_ADD_STR。键值为字符串指针时使用HASH_ADD_KEYPTR。接下来给出两个例子参考。
当结构体中的键值为字符串数组时
1#include <string.h> /* strcpy */ 2#include <stdlib.h> /* malloc */ 3#include <stdio.h> /* printf */ 4#include "uthash.h" 5 6struct my_struct { 7 char name[10]; /* key (string is WITHIN the structure) */ 8 int id; 9 UT_hash_handle hh; /* makes this structure hashable */ 10}; 11 12 13int main(int argc, char *argv[]) { 14 const char *names[] = { "joe", "bob", "betty", NULL }; 15 struct my_struct *s, *tmp, *users = NULL; 16 17 for (int i = 0; names[i]; ++i) { 18 s = (struct my_struct *)malloc(sizeof *s); 19 strcpy(s->name, names[i]); 20 s->id = i; 21 HASH_ADD_STR( users, name, s ); 22 } 23 24 HASH_FIND_STR( users, "betty", s); 25 if (s) printf("betty's id is %d\n", s->id); 26 27 /* free the hash table contents */ 28 HASH_ITER(hh, users, s, tmp) { 29 HASH_DEL(users, s); 30 free(s); 31 } 32 return 0; 33}
当结构体中的键值为字符串指针时
1#include <string.h> /* strcpy */ 2#include <stdlib.h> /* malloc */ 3#include <stdio.h> /* printf */ 4#include "uthash.h" 5 6struct my_struct { 7 const char *name; /* key */ 8 int id; 9 UT_hash_handle hh; /* makes this structure hashable */ 10}; 11 12 13int main(int argc, char *argv[]) { 14 const char *names[] = { "joe", "bob", "betty", NULL }; 15 struct my_struct *s, *tmp, *users = NULL; 16 17 for (int i = 0; names[i]; ++i) { 18 s = (struct my_struct *)malloc(sizeof *s); 19 s->name = names[i]; 20 s->id = i; 21 HASH_ADD_KEYPTR( hh, users, s->name, strlen(s->name), s ); 22 } 23 24 HASH_FIND_STR( users, "betty", s); 25 if (s) printf("betty's id is %d\n", s->id); 26 27 /* free the hash table contents */ 28 HASH_ITER(hh, users, s, tmp) { 29 HASH_DEL(users, s); 30 free(s); 31 } 32 return 0; 33}
指针键值
1#include <stdio.h> 2#include <stdlib.h> 3#include "uthash.h" 4 5typedef struct { 6 void *key; 7 int i; 8 UT_hash_handle hh; 9} el_t; 10 11el_t *hash = NULL; 12char *someaddr = NULL; 13 14int main() { 15 el_t *d; 16 el_t *e = (el_t *)malloc(sizeof *e); 17 if (!e) return -1; 18 e->key = (void*)someaddr; 19 e->i = 1; 20 HASH_ADD_PTR(hash,key,e); 21 HASH_FIND_PTR(hash, &someaddr, d); 22 if (d) printf("found\n"); 23 24 /* release memory */ 25 HASH_DEL(hash,e); 26 free(e); 27 return 0; 28}
结构体键值
在将项目添加到哈希或查找项目之前,必须将结构体键值中的元素清零。
1#include <stdlib.h> 2#include <stdio.h> 3#include "uthash.h" 4 5typedef struct { 6 char a; 7 int b; 8} record_key_t; 9 10typedef struct { 11 record_key_t key; 12 /* ... other data ... */ 13 UT_hash_handle hh; 14} record_t; 15 16int main(int argc, char *argv[]) { 17 record_t l, *p, *r, *tmp, *records = NULL; 18 19 r = (record_t *)malloc(sizeof *r); 20 /*结构体键值清零*/ 21 memset(r, 0, sizeof *r); 22 r->key.a = 'a'; 23 r->key.b = 1; 24 HASH_ADD(hh, records, key, sizeof(record_key_t), r); 25 26 memset(&l, 0, sizeof(record_t)); 27 l.key.a = 'a'; 28 l.key.b = 1; 29 HASH_FIND(hh, records, &l.key, sizeof(record_key_t), p); 30 31 if (p) printf("found %c %d\n", p->key.a, p->key.b); 32 33 HASH_ITER(hh, records, p, tmp) { 34 HASH_DEL(records, p); 35 free(p); 36 } 37 return 0; 38}
常用宏参考
类型宏
1HASH_ADD_INT(head, keyfield_name, item_ptr) 2 3HASH_REPLACE_INT(head, keyfiled_name, item_ptr,replaced_item_ptr) 4 5HASH_FIND_INT(head, key_ptr, item_ptr) 6 7HASH_ADD_STR(head, keyfield_name, item_ptr) 8 9HASH_REPLACE_STR(head,keyfield_name, item_ptr, replaced_item_ptr) 10 11HASH_FIND_STR(head, key_ptr, item_ptr) 12 13HASH_ADD_PTR(head, keyfield_name, item_ptr) 14 15HASH_REPLACE_PTR(head, keyfield_name, item_ptr, replaced_item_ptr) 16 17HASH_FIND_PTR(head, key_ptr, item_ptr) 18 19HASH_DEL(head, item_ptr) 20 21HASH_SORT(head, cmp) 22 23HASH_COUNT(head)
通用宏
1HASH_ADD(hh_name, head, keyfield_name, key_len, item_ptr) 2 3HASH_ADD_BYHASHVALUE(hh_name, head, keyfield_name, key_len, hashv, item_ptr) 4 5HASH_ADD_KEYPTR(hh_name, head, key_ptr, key_len, item_ptr) 6 7HASH_ADD_KEYPTR_BYHASHVALUE(hh_name, head, key_ptr, key_len, hashv, item_ptr) 8 9HASH_ADD_INORDER(hh_name, head, keyfield_name, key_len, item_ptr, cmp) 10 11HASH_ADD_BYHASHVALUE_INORDER(hh_name, head, keyfield_name, key_len, hashv, item_ptr, cmp) 12 13HASH_ADD_KEYPTR_INORDER(hh_name, head, key_ptr, key_len, item_ptr, cmp) 14 15HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh_name, head, key_ptr, key_len, hashv, item_ptr, cmp) 16 17HASH_REPLACE(hh_name, head, keyfield_name, key_len, item_ptr, replaced_item_ptr) 18 19HASH_REPLACE_BYHASHVALUE(hh_name, head, keyfield_name, key_len, hashv, item_ptr, replaced_item_ptr) 20 21HASH_REPLACE_INORDER(hh_name, head, keyfield_name, key_len, item_ptr, replaced_item_ptr, cmp) 22 23HASH_REPLACE_BYHASHVALUE_INORDER(hh_name, head, keyfield_name, key_len, hashv, item_ptr, replaced_item_ptr, cmp) 24 25HASH_FIND(hh_name, head, key_ptr, key_len, item_ptr) 26 27HASH_FIND_BYHASHVALUE(hh_name, head, key_ptr, key_len, hashv, item_ptr) 28 29HASH_DELETE(hh_name, head, item_ptr) 30 31HASH_VALUE(key_ptr, key_len, hashv) 32 33HASH_SRT(hh_name, head, cmp) 34 35HASH_CNT(hh_name, head) 36 37HASH_CLEAR(hh_name, head) 38 39HASH_SELECT(dst_hh_name, dst_head, src_hh_name, src_head, condition) 40 41HASH_ITER(hh_name, head, item_ptr, tmp_item_ptr) 42 43HASH_OVERHEAD(hh_name, head)
参数说明
参数说明
hh_name
UT_hash_handle结构中字段的 名称。俗称 hh。
head
结构指针变量,用作哈希的“头”。如此命名是因为它最初指向添加到哈希中的第一项。
keyfield_name
结构中键字段的名称。(对于多字段键,这是键的第一个字段)。如果您不熟悉宏,则将字段名称作为参数传递似乎很奇怪。请参阅 注释。
key_len
键字段的长度(以字节为单位)。例如,对于整数键,它是 sizeof(int),而对于字符串键,它是strlen(key)。(有关多字段键,请参阅此注释。)
key_ptr
对于HASH_FIND,这是指向要在哈希中查找的键的指针(由于它是指针,因此您不能在此处直接传递文字值)。对于 HASH_ADD_KEYPTR,这是要添加的项的键的地址。
hashv
提供的键的哈希值。这是…_BYHASHVALUE宏的输入参数,是 的输出参数HASH_VALUE。如果您要重复查找相同的键,则重用缓存的哈希值可以优化性能。
item_ptr
指向要添加,删除,替换或查找的结构的指针,或迭代期间的当前指针。这是一个输入参数HASH_ADD, HASH_DELETE和HASH_REPLACE宏,和用于输出参数HASH_FIND 和HASH_ITER。(当HASH_ITER用于迭代时,tmp_item_ptr 是与item_ptr内部使用的类型相同的另一个变量)。
replace_item_ptr
用于HASH_REPLACE宏。这是一个输出参数,设置为指向替换的项目(如果没有替换的项目,则设置为NULL)。
cmp
指向比较函数的指针,该函数接受两个参数(指向要比较的项目的指针),并返回一个int值,该值指定第一个项目应在第二个项目之前,等于还是之后排序(如strcmp)。
condition
接受单个参数的函数或宏(指向结构的空指针,需要将其强制转换为适当的结构类型)。如果应“选择”结构以将其添加到目标哈希中,则函数或宏的值应为非零值。