现在的位置: 首页 > 综合 > 正文

uthash

2017年10月10日 ⁄ 综合 ⁄ 共 10885字 ⁄ 字号 评论关闭

一、哈希表的概念及作用

        在一般的线性表或者树中,我们所储存的值写它的存储位置的关系是随机的。因此,在查找过程中,需要一系列的与关键字的比较。算法的时间复杂度与比较的次数有关。线性表查找的时间复杂度为O(n)而平衡二叉树的查找的时间复杂度为O(log(n))。无论是采用线程表或是树进行存储,都面临面随着数据量的增大,查找速度将不同程度变慢的问题。而哈希表正好解决了这个问题。它的主要思想是通过将值与其存储位置相关联,来实现快速的随机存储。

关于哈希表的详细说明,可以参考以下链接:

http://zh.wikipedia.org/zh-cn/%E5%93%88%E5%B8%8C%E8%A1%A8

  http://en.wikipedia.org/wiki/Hash_table

二、uthash的基本用法

由于C语言中,并没有对hash表这类的高级数据结构进行支持,即使在目前通用的C++中,也只支持栈、队列等几个数据结构,对于map,其实是以树结构来实现的,而不是以hash表实现。

uthash是一个C语言的hash表实现。它以宏定义的方式实现hash表,不仅加快了运行的速度,而且与关键类型无关的优点。

uthash使用起来十分方便,只要将头文件uthash.h包含进去就可以使用。

目前,uthash的最新版本(1.9)支持如下平台:

  • Linux
  •   Mac OS X
  • Windows using vs2008 and vs 2010
  • Solaris
  • OpenBSD

 

      通常这足够通用了。唯一的不足是在windows下,在uthash这旧版本中,并不支持vs2008和2010,而是支持MinGW。

 uthash支持:增加、查找、删除、计数、迭代、排序、选择等操作。

第一步:包含头文件

  1. #include "uthash.h"  

 

第二步:自定义数据结构。每个结构代表一个键-值对,并且,每个结构中要有一个UT_hash_handle成员。

  1. struct my_struct {  
  2. int id; /* key */  
  3. char name[10];  
  4. UT_hash_handle hh; /* makes this structure hashable */  
  5. };  

 

第三步:定义hash表指针。这个指针为前面自定义数据结构的指针,并初始化为NULL。

  1. struct my_struct *users = NULL; /* important! initialize to NULL */  

 

第四步:进行一般的操作。

增加:

  1. int add_user(int user_id, char *name) {  
  2. struct my_struct *s;  
  3. s = malloc(sizeof(struct my_struct));  
  4. s->id = user_id;  
  5. strcpy(s->name, name);  
  6. HASH_ADD_INT( users, id, s ); /* id: name of key field */  
  7. }  

 

查找:

  1. struct 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. }  

 

删除:

  1. void 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. }  

 

计数:

  1. unsigned int num_users;  
  2. num_users = HASH_COUNT(users);  
  3. printf("there are %u users/n", num_users);  

 

迭代:

  1. void print_users() {  
  2. struct my_struct *s;  
  3. for(s=users; s != NULL; s=s->hh.next) {  
  4. printf("user id %d: name %s/n", s->id, s->name  
  5. }  
  6. }  

 

排序:

  1. int name_sort(struct my_struct *a, struct my_struct *b) {  
  2. return strcmp(a->name,b->name);  
  3. }  
  4. int id_sort(struct my_struct *a, struct my_struct *b) {  
  5. return (a->id - b->id);  
  6. }  
  7. void sort_by_name() {  
  8. HASH_SORT(users, name_sort);  
  9. }  
  10. void sort_by_id() {  
  11. HASH_SORT(users, id_sort);  
  12. }  

 

要注意,在uthash中,并不会对其所储存的值进行移动或者复制,也不会进行内存的释放。

 

 

 

 

三、uthash的高级用法

第一、关于键

对于uthash来说,键只是一系列的字节。所以,我们可以使用任意类型的键。包括:整形,字符串,结构等。uthash并不建议以浮点数作为键。若键的类型是结构体,那么在加入到hash表前,要对无关的数据进行清零。例如我们定义如下结构体:

  1. typedef struct { /* this structure will be our key */  
  2. char a;  
  3. int b;  
  4. } record_key_t;  

 

由于系统会自动进行字节对齐,也就是在a后面加入3个点位的字节。所以,在将类型为record_key_t*的数据加入到hash表前,一定要保证该数据的无关字节的值为0,否则将可能造成存入的键值无法被查找到的情况。

下面是一段使用结构体作为键的类型的代码:

  1. #include <stdlib.h>  
  2. #include <stdio.h>  
  3. #include "uthash.h"  
  4. typedef struct { /* this structure will be our key */  
  5. char a;  
  6. int b;  
  7. } record_key_t;  
  8. typedef struct { /* the hash is comprised of these */  
  9. record_key_t key;  
  10. /* ... other data ... */  
  11. UT_hash_handle hh;  
  12. } record_t;  
  13. int main(int argc, char *argv[]) {  
  14. record_t l, *p, *r, *records = NULL;  
  15. r = (record_t*)malloc( sizeof(record_t) );  
  16. memset(r, 0, sizeof(record_t)); /* zero fill! */  
  17. r->key.a = ’a’;  
  18. r->key.b = 1;  
  19. HASH_ADD(hh, records, key, sizeof(record_key_t), r);  
  20. memset(&l, 0, sizeof(record_t)); /* zero fill! */  
  21. l.key.a = ’a’;  
  22. l.key.b = 1;  
  23. HASH_FIND(hh, records, &l.key, sizeof(record_key_t), p);  
  24. if (p) printf("found %c %d/n", p->key.a, p->key.b);  
  25. return 0;  
  26. }  

 

uthash中还支持组合键,但是要求组合键的存储位置是相邻的。所谓的组合键也是利用了uthash把一切的键都看作是字节序列的原理,我们只要将组合键的第一个字段和整个组合键的长度正确的填入相关的函数就可以了。例子如下:

  1. #include <stdlib.h>    /* malloc       */  
  2. #include <stddef.h>    /* offsetof     */  
  3. #include <stdio.h>     /* printf       */  
  4. #include <string.h>    /* memset       */  
  5. #include "uthash.h"  
  6. #define UTF32 1  
  7. typedef struct {  
  8.   UT_hash_handle hh;  
  9.   int len;  
  10.   char encoding;      /* these two fields */  
  11.   int text[];         /* comprise the key */  
  12. } msg_t;  
  13. typedef struct {  
  14.     char encoding;   
  15.     int text[];   
  16. } lookup_key_t;  
  17. int main(int argc, char *argv[]) {  
  18.     unsigned keylen;  
  19.     msg_t *msg, *msgs = NULL;  
  20.     lookup_key_t *lookup_key;  
  21.     int beijing[] = {0x5317, 0x4eac};   /* UTF-32LE for 鍖椾含 */  
  22.     /* allocate and initialize our structure */  
  23.     msg = (msg_t*)malloc( sizeof(msg_t) + sizeof(beijing) );  
  24.     memset(msg, 0, sizeof(msg_t)+sizeof(beijing)); /* zero fill */  
  25.     msg->len = sizeof(beijing);  
  26.     msg->encoding = UTF32;  
  27.     memcpy(msg->text, beijing, sizeof(beijing));  
  28.     /* calculate the key length including padding, using formula */  
  29.     keylen =   offsetof(msg_t, text)       /* offset of last key field */  
  30.              + sizeof(beijing)             /* size of last key field */  
  31.              - offsetof(msg_t, encoding);  /* offset of first key field */  
  32.     /* add our structure to the hash table */  
  33.     HASH_ADD( hh, msgs, encoding, keylen, msg);  
  34.     /* look it up to prove that it worked :-) */  
  35.     msg=NULL;  
  36.     lookup_key = (lookup_key_t*)malloc(sizeof(*lookup_key) + sizeof(beijing));  
  37.     memset(lookup_key, 0, sizeof(*lookup_key) + sizeof(beijing));  
  38.     lookup_key->encoding = UTF32;  
  39.     memcpy(lookup_key->text, beijing, sizeof(beijing));  
  40.     HASH_FIND( hh, msgs, &lookup_key->encoding, keylen, msg );  
  41.     if (msg) printf("found /n");  
  42.     free(lookup_key);  
  43.     return 0;  
  44. }  

 

第二、uthash支持将一个结构体变量存储在不同的hash表里,并且可以指定不同的字段做为键。例如:

  1. struct my_struct {  
  2. int id; /* usual key */  
  3. char username[10]; /* alternative key */  
  4. UT_hash_handle hh1; /* handle for first hash table */  
  5. UT_hash_handle hh2; /* handle for second hash table */  
  6. };  
  7. struct my_struct *users_by_id = NULL, *users_by_name = NULL, *s;  
  8. int i;  
  9. char *name;  
  10. s = malloc(sizeof(struct my_struct));  
  11. s->id = 1;  
  12. strcpy(s->username, "thanson");  
  13. /* add the structure to both hash tables */  
  14. HASH_ADD(hh1, users_by_id, id, sizeof(int), s);  
  15. HASH_ADD(hh2, users_by_name, username, strlen(s->username), s);  
  16. /* lookup user by ID in the "users_by_id" hash table */  
  17. i=1;  
  18. HASH_FIND(hh1, users_by_id, &i, sizeof(int), s);  
  19. if (s) printf("found id %d: %s/n", i, s->username);  
  20. /* lookup user by username in the "users_by_name" hash table */  
  21. name = "thanson";  
  22. HASH_FIND(hh2, users_by_name, name, strlen(name), s);  
  23. if (s) printf("found user %s: %d/n", name, s->id);  

 

注意,若要将结构体变量存储在不同的hash表里,需要在该结构体中为每个hash表定义一个UT_hash_handle字段。

 

第三、选择。简单来说,select就是在一个hash表选择出一批数据,加入到另一个hash表中。它比用HASH_ADD更快。例子如下:

  1. #include "uthash.h"  
  2. #include <stdlib.h>   /* malloc */  
  3. #include <stdio.h>    /* printf */  
  4. typedef struct {  
  5.     int id;  
  6.     UT_hash_handle hh;  
  7.     UT_hash_handle ah;  
  8. } example_user_t;  
  9. #define EVENS(x) (((x)->id & 1) == 0)  
  10. int evens(void *userv) {  
  11.   example_user_t *user = (example_user_t*)userv;  
  12.   return ((user->id & 1) ? 0 : 1);  
  13. }  
  14. int idcmp(void *_a, void *_b) {  
  15.   example_user_t *a = (example_user_t*)_a;  
  16.   example_user_t *b = (example_user_t*)_b;  
  17.   return (a->id - b->id);  
  18. }  
  19. int main(int argc,char *argv[]) {  
  20.     int i;  
  21.     example_user_t *user, *users=NULL, *ausers=NULL;  
  22.     /* create elements */  
  23.     for(i=0;i<10;i++) {  
  24.         user = (example_user_t*)malloc(sizeof(example_user_t));  
  25.         user->id = i;  
  26.         HASH_ADD_INT(users,id,user);  
  27.     }  
  28.     for(user=users; user; user=(example_user_t*)(user->hh.next)) {  
  29.         printf("user %d/n", user->id);  
  30.     }  
  31.     /* now select some users into ausers */  
  32.     HASH_SELECT(ah,ausers,hh,users,evens);  
  33.     HASH_SRT(ah,ausers,idcmp);  
  34.     for(user=ausers; user; user=(example_user_t*)(user->ah.next)) {  
  35.         printf("auser %d/n", user->id);  
  36.     }  
  37.    return 0;  
  38. }  

 

第四、内置hash函数。uthash支持如下几种hash函数:

  1. Symbol Name  
  2. JEN Jenkins (default)  
  3. BER Bernstein  
  4. SAX Shift-Add-Xor  
  5. OAT One-at-a-time  
  6. FNV Fowler/Noll/Vo  
  7. SFH Paul Hsieh  
  8. MUR MurmurHash (see note)  

 

编译代码时,可以选择不同的hash函数,只要在编译时指定就可以了。例如:

  1. cc -DHASH_FUNCTION=HASH_BER -o program program.c  

 

第五、线程。uthash是非线程安全的,所以如要在多线程中进行使用,必须对操作进行加锁。例如:

首先初始化锁

  1. pthread_rwlock_t lock;  
  2. if (pthread_rwlock_init(&lock,NULL) != 0) fatal("can’t create rwlock");  

 

如果进行查找操作

  1. if (pthread_rwlock_rdlock(&lock) != 0) fatal("can’t get rdlock");  
  2. HASH_FIND_INT(elts, &i, e);  
  3. pthread_rwlock_unlock(&lock);  

 

如果进行删除操作

  1. if (pthread_rwlock_wrlock(&lock) != 0) fatal("can’t get wrlock");  
  2. HASH_DEL(elts, e);  
  3. pthread_rwlock_unlock(&lock);  

----------------------------------------------------------------------------------------------------------------

demo:

  1. #include "uthash.h"  
  2. #include <stdio.h>  
  3. #include <stdlib.h>  
  4. #include <unistd.h>  
  5.   
  6.   
  7. /*这个uthash必须构造一个结构体*/  
  8. struct packet  
  9. {  
  10.         int key;       /*这个是用来做hash的key值*/  
  11.         char msg[10];   
  12.         UT_hash_handle hh; /*这个结构是uthash的结构体,里面包含next,prev,hash值等信息*/  
  13. };  
  14.   
  15. int main()  
  16. {  
  17.         struct packet *pkt, *tmp;  
  18.         int i;  
  19.   
  20.         struct packet *hash_packet = NULL; /*必须初始化为NULL*/  
  21.           
  22.   
  23.   
  24.         /*打印这个hash的节点数*/  
  25.         printf ("hash count = %d \n", HASH_COUNT(hash_packet));  
  26.   
  27.   
  28.   
  29.   
  30.         /*往hash中添加节点*/  
  31.   
  32.         for (i=0; i<10; i++)  
  33.         {  
  34.                 pkt = (struct packet *)malloc(sizeof(struct packet));  
  35.                 pkt->key=i;  
  36.                 sprintf (pkt->msg, "i=%d", i);  
  37.   
  38.                 HASH_FIND_INT(hash_packet, &i, tmp);  
  39.                 if (tmp != NULL)  
  40.                 {  
  41.                         printf ("The key(%d) exists in hash. \n", i);  
  42.                         continue;  
  43.                 }  
  44.                 HASH_ADD_INT(hash_packet, key, pkt);  
  45.                 printf ("insert item. key=%d,value=%p \n", i, pkt);  
  46.         }  
  47.         printf ("hash count = %d \n", HASH_COUNT(hash_packet));  
  48.   
  49.   
  50.   
  51.   
  52.         /*通过key查找*/  
  53.         for (i=0; i<13; i++)  
  54.         {  
  55.                 HASH_FIND_INT(hash_packet, &i, tmp);  
  56.                 if (tmp == NULL)  
  57.                 {  
  58.                         printf ("find not item. key=%d,value=%p \n", i, tmp);  
  59.                         continue;  
  60.                 }  
  61.                 printf ("find item. key=%d,value=%p \n", i, tmp);  
  62.         }  
  63.   
  64.         printf ("hash count = %d \n", HASH_COUNT(hash_packet));  
  65.   
  66.   
  67.   
  68.   
  69.         /*遍历这个hash表*/  
  70.         for (tmp=hash_packet; tmp != NULL; tmp=tmp->hh.next)  
  71.                 printf (" %d => %s \n", tmp->key, tmp->msg);  
  72.         /*删除节点*/  
  73.         for (i=0; i<13; i++)  
  74.         {  
  75.                 HASH_FIND_INT(hash_packet, &i, tmp);  
  76.                 if (tmp == NULL)  
  77.                 {  
  78.                         printf ("find not item. key=%d,value=%p \n", i, tmp);  
  79.                         continue;  
  80.                 }  
  81.   
  82.                 /*删除节点不会释放你的空间必须自己释放*/  
  83.                 HASH_DEL(hash_packet, tmp);  
  84.                 free(tmp);  
  85.                 printf ("delete itme. key=%d,value=%p \n", i, tmp);  
  86.         }  
  87.         printf ("hash count = %d \n", HASH_COUNT(hash_packet));  
  88.         return 0;  

【上篇】
【下篇】

抱歉!评论已关闭.