因爲C語言自己不存在哈希,可是當須要使用哈希表的時候本身構建哈希會異常複雜。所以,咱們能夠調用開源的第三方頭文件,這只是一個頭文件:uthash.h。咱們須要作的就是將頭文件複製到您的項目中,而後:#include "uthash.h"。因爲uthash僅是頭文件,所以沒有可連接的庫代碼。git
使用uthash添加,查找和刪除一般是常數時間的操做,此哈希的目標是簡約高效。它大約有1000行C。它會自動內聯,由於它是做爲宏實現的。
uthash還包括三個額外的頭文件,主要提供鏈表,動態數組和字符串。utlist.h爲C結構提供了連接列表宏。utarray.h使用宏實現動態數組。utstring.h實現基本的動態字符串。
github下載連接:https://github.com/troydhanson/uthashgithub
這裏咱們將id做爲一個索引值,也就是鍵值,將name做爲value。數組
#include "uthash.h" struct my_struct { int id; /* key */ char name[10]; UT_hash_handle hh; /* makes this structure hashable */ }; /*聲明哈希爲NULL指針*/ struct 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表示添加的鍵值能夠是任意類型app
void add_user(int user_id, char *name) { struct my_struct *s; /*重複性檢查,當把兩個相同key值的結構體添加到哈希表中時會報錯*/ HASH_FIND_INT(users, &user_id, s); /* id already in the hash? */ /*只有在哈希中不存在ID的狀況下,咱們才建立該項目並將其添加。不然,咱們只修改已經存在的結構。*/ if (s==NULL) { s = (struct my_struct *)malloc(sizeof *s); s->id = user_id; HASH_ADD_INT( users, id, s ); /* id: name of key field */ } strcpy(s->name, name); }
HASH_ADD_INT函數中,第一個參數users是哈希表,第二個參數id是鍵字段的名稱。最後一個參數s是指向要添加的結構的指針。函數
struct my_struct *find_user(int user_id) { struct my_struct *s; HASH_FIND_INT( users, &user_id, s ); /* s: output pointer */ return s; }
在上述代碼中,第一個參數users是哈希表,第二個參數是user_id的地址(必定要傳遞地址)。最後s是輸出變量。當能夠在哈希表中找到相應鍵值時,s返回給定鍵的結構,當找不到時s返回NULL。性能
HASH_REPLACE宏等效於HASH_ADD宏,HASH_REPLACE會嘗試查找和刪除項目外。若是找到並刪除了一個項目,它還將返回該項目的指針做爲輸出參數。優化
void replace_user(HashHead *head, HashNode *newNode) { HashNode *oldNode = find_user(*head, newNode->id); if (oldNode) HASH_REPLACE_INT(*head, id, newNode, oldNode); }
要從哈希表中刪除結構,必須具備指向它的指針。(若是隻有鍵,請先執行HASH_FIND以獲取結構指針)。ui
void delete_user(struct my_struct *user) { HASH_DEL(users, user); /* user: pointer to deletee */ free(user); /* optional; it's up to you! */ }
一樣,這裏users是哈希表,user是指向咱們要從哈希中刪除的結構的指針。this
刪除結構只是將其從哈希表中刪除,並不是free 。什麼時候釋放結構的選擇徹底取決於本身;uthash永遠不會釋放您的結構
HASH_ITER是一個宏定義,程序執行時被替換爲一個循環。
void delete_all() { struct my_struct *current_user, *tmp; HASH_ITER(hh, users, current_user, tmp) { HASH_DEL(users,current_user); /* delete; users advances to next */ free(current_user); /* optional- if you want to free */ } }
若是您只想刪除全部項目,但不釋放它們或進行每一個元素的清理,則能夠經過一次操做更有效地作到這一點:
HASH_CLEAR(hh,users);
以後,列表頭(此處爲users)將設置爲NULL。
unsigned int num_users; num_users = HASH_COUNT(users); printf("there are %u users\n", num_users);
當users爲NULL時,HASH_COUNT會返回0.
void print_users() { struct my_struct *s; for(s=users; s != NULL; s=s->hh.next) { printf("user id %d: name %s\n", s->id, s->name); } }
還有一個hh.prev指針,可用於從任何已知項開始向後迭代哈希。
因爲hh.prev和hh.next字段的緣故,能夠在哈希中向前和向後迭代。能夠經過重複跟隨這些指針來訪問哈希中的全部項目,所以哈希也是雙鏈表。
HASH_SORT( users, name_sort );
第二個參數是指向比較函數的指針。它必須接受兩個指針參數(要比較的項目),而且若是第一個項目分別在第二個項目以前,等於或以後排序,則必須返回小於零,零或大於零的int。 (這與標準C庫中的strcmp或qsort使用的約定相同)。
int sort_function(void *a, void *b) { /* compare a to b (cast a and b appropriately) * return (int) -1 if (a < b) * return (int) 0 if (a == b) * return (int) 1 if (a > b) */ }
name_sort和id_sort的兩個排序函數示例。
int name_sort(struct my_struct *a, struct my_struct *b) { return strcmp(a->name,b->name); } int id_sort(struct my_struct *a, struct my_struct *b) { return (a->id - b->id); } void sort_by_name() { HASH_SORT(users, name_sort); } void sort_by_id() { HASH_SORT(users, id_sort); }
#include <stdio.h> /* gets */ #include <stdlib.h> /* atoi, malloc */ #include <string.h> /* strcpy */ #include "uthash.h" struct my_struct { int id; /* key */ char name[10]; UT_hash_handle hh; /* makes this structure hashable */ }; struct my_struct *users = NULL; void add_user(int user_id, char *name) { struct my_struct *s; HASH_FIND_INT(users, &user_id, s); /* id already in the hash? */ if (s==NULL) { s = (struct my_struct *)malloc(sizeof *s); s->id = user_id; HASH_ADD_INT( users, id, s ); /* id: name of key field */ } strcpy(s->name, name); } struct my_struct *find_user(int user_id) { struct my_struct *s; HASH_FIND_INT( users, &user_id, s ); /* s: output pointer */ return s; } void delete_user(struct my_struct *user) { HASH_DEL(users, user); /* user: pointer to deletee */ free(user); } void delete_all() { struct my_struct *current_user, *tmp; HASH_ITER(hh, users, current_user, tmp) { HASH_DEL(users, current_user); /* delete it (users advances to next) */ free(current_user); /* free it */ } } void print_users() { struct my_struct *s; for(s=users; s != NULL; s=(struct my_struct*)(s->hh.next)) { printf("user id %d: name %s\n", s->id, s->name); } } int name_sort(struct my_struct *a, struct my_struct *b) { return strcmp(a->name,b->name); } int id_sort(struct my_struct *a, struct my_struct *b) { return (a->id - b->id); } void sort_by_name() { HASH_SORT(users, name_sort); } void sort_by_id() { HASH_SORT(users, id_sort); } int main(int argc, char *argv[]) { char in[10]; int id=1, running=1; struct my_struct *s; unsigned num_users; while (running) { printf(" 1. add user\n"); printf(" 2. add/rename user by id\n"); printf(" 3. find user\n"); printf(" 4. delete user\n"); printf(" 5. delete all users\n"); printf(" 6. sort items by name\n"); printf(" 7. sort items by id\n"); printf(" 8. print users\n"); printf(" 9. count users\n"); printf("10. quit\n"); gets(in); switch(atoi(in)) { case 1: printf("name?\n"); add_user(id++, gets(in)); break; case 2: printf("id?\n"); gets(in); id = atoi(in); printf("name?\n"); add_user(id, gets(in)); break; case 3: printf("id?\n"); s = find_user(atoi(gets(in))); printf("user: %s\n", s ? s->name : "unknown"); break; case 4: printf("id?\n"); s = find_user(atoi(gets(in))); if (s) delete_user(s); else printf("id unknown\n"); break; case 5: delete_all(); break; case 6: sort_by_name(); break; case 7: sort_by_id(); break; case 8: print_users(); break; case 9: num_users=HASH_COUNT(users); printf("there are %u users\n", num_users); break; case 10: running=0; break; } } delete_all(); /* free any structures */ return 0; }
當鍵值爲整型時,可使用HASH_ADD_INT和HASH_FIND_INT。(對於全部類型的鍵,其餘操做(例如HASH_DELETE和)HASH_SORT都是相同的)。
當鍵值爲字符串時,具體要使用那個函數取決於結構體中的鍵值爲字符串數組仍是字符串指針。 這一點很重要。當結構體中的鍵值爲字符串數組時,使用HASH_ADD_STR。鍵值爲字符串指針時使用HASH_ADD_KEYPTR。接下來給出兩個例子參考。
當結構體中的鍵值爲字符串數組時
#include <string.h> /* strcpy */ #include <stdlib.h> /* malloc */ #include <stdio.h> /* printf */ #include "uthash.h" struct my_struct { char name[10]; /* key (string is WITHIN the structure) */ int id; UT_hash_handle hh; /* makes this structure hashable */ }; int main(int argc, char *argv[]) { const char *names[] = { "joe", "bob", "betty", NULL }; struct my_struct *s, *tmp, *users = NULL; for (int i = 0; names[i]; ++i) { s = (struct my_struct *)malloc(sizeof *s); strcpy(s->name, names[i]); s->id = i; HASH_ADD_STR( users, name, s ); } HASH_FIND_STR( users, "betty", s); if (s) printf("betty's id is %d\n", s->id); /* free the hash table contents */ HASH_ITER(hh, users, s, tmp) { HASH_DEL(users, s); free(s); } return 0; }
當結構體中的鍵值爲字符串指針時
#include <string.h> /* strcpy */ #include <stdlib.h> /* malloc */ #include <stdio.h> /* printf */ #include "uthash.h" struct my_struct { const char *name; /* key */ int id; UT_hash_handle hh; /* makes this structure hashable */ }; int main(int argc, char *argv[]) { const char *names[] = { "joe", "bob", "betty", NULL }; struct my_struct *s, *tmp, *users = NULL; for (int i = 0; names[i]; ++i) { s = (struct my_struct *)malloc(sizeof *s); s->name = names[i]; s->id = i; HASH_ADD_KEYPTR( hh, users, s->name, strlen(s->name), s ); } HASH_FIND_STR( users, "betty", s); if (s) printf("betty's id is %d\n", s->id); /* free the hash table contents */ HASH_ITER(hh, users, s, tmp) { HASH_DEL(users, s); free(s); } return 0; }
#include <stdio.h> #include <stdlib.h> #include "uthash.h" typedef struct { void *key; int i; UT_hash_handle hh; } el_t; el_t *hash = NULL; char *someaddr = NULL; int main() { el_t *d; el_t *e = (el_t *)malloc(sizeof *e); if (!e) return -1; e->key = (void*)someaddr; e->i = 1; HASH_ADD_PTR(hash,key,e); HASH_FIND_PTR(hash, &someaddr, d); if (d) printf("found\n"); /* release memory */ HASH_DEL(hash,e); free(e); return 0; }
在將項目添加到哈希或查找項目以前,必須將結構體鍵值中的元素清零。
#include <stdlib.h> #include <stdio.h> #include "uthash.h" typedef struct { char a; int b; } record_key_t; typedef struct { record_key_t key; /* ... other data ... */ UT_hash_handle hh; } record_t; int main(int argc, char *argv[]) { record_t l, *p, *r, *tmp, *records = NULL; r = (record_t *)malloc(sizeof *r); /*結構體鍵值清零*/ memset(r, 0, sizeof *r); r->key.a = 'a'; r->key.b = 1; HASH_ADD(hh, records, key, sizeof(record_key_t), r); memset(&l, 0, sizeof(record_t)); l.key.a = 'a'; l.key.b = 1; HASH_FIND(hh, records, &l.key, sizeof(record_key_t), p); if (p) printf("found %c %d\n", p->key.a, p->key.b); HASH_ITER(hh, records, p, tmp) { HASH_DEL(records, p); free(p); } return 0; }
HASH_ADD_INT(head, keyfield_name, item_ptr) HASH_REPLACE_INT(head, keyfiled_name, item_ptr,replaced_item_ptr) HASH_FIND_INT(head, key_ptr, item_ptr) HASH_ADD_STR(head, keyfield_name, item_ptr) HASH_REPLACE_STR(head,keyfield_name, item_ptr, replaced_item_ptr) HASH_FIND_STR(head, key_ptr, item_ptr) HASH_ADD_PTR(head, keyfield_name, item_ptr) HASH_REPLACE_PTR(head, keyfield_name, item_ptr, replaced_item_ptr) HASH_FIND_PTR(head, key_ptr, item_ptr) HASH_DEL(head, item_ptr) HASH_SORT(head, cmp) HASH_COUNT(head)
HASH_ADD(hh_name, head, keyfield_name, key_len, item_ptr) HASH_ADD_BYHASHVALUE(hh_name, head, keyfield_name, key_len, hashv, item_ptr) HASH_ADD_KEYPTR(hh_name, head, key_ptr, key_len, item_ptr) HASH_ADD_KEYPTR_BYHASHVALUE(hh_name, head, key_ptr, key_len, hashv, item_ptr) HASH_ADD_INORDER(hh_name, head, keyfield_name, key_len, item_ptr, cmp) HASH_ADD_BYHASHVALUE_INORDER(hh_name, head, keyfield_name, key_len, hashv, item_ptr, cmp) HASH_ADD_KEYPTR_INORDER(hh_name, head, key_ptr, key_len, item_ptr, cmp) HASH_ADD_KEYPTR_BYHASHVALUE_INORDER(hh_name, head, key_ptr, key_len, hashv, item_ptr, cmp) HASH_REPLACE(hh_name, head, keyfield_name, key_len, item_ptr, replaced_item_ptr) HASH_REPLACE_BYHASHVALUE(hh_name, head, keyfield_name, key_len, hashv, item_ptr, replaced_item_ptr) HASH_REPLACE_INORDER(hh_name, head, keyfield_name, key_len, item_ptr, replaced_item_ptr, cmp) HASH_REPLACE_BYHASHVALUE_INORDER(hh_name, head, keyfield_name, key_len, hashv, item_ptr, replaced_item_ptr, cmp) HASH_FIND(hh_name, head, key_ptr, key_len, item_ptr) HASH_FIND_BYHASHVALUE(hh_name, head, key_ptr, key_len, hashv, item_ptr) HASH_DELETE(hh_name, head, item_ptr) HASH_VALUE(key_ptr, key_len, hashv) HASH_SRT(hh_name, head, cmp) HASH_CNT(hh_name, head) HASH_CLEAR(hh_name, head) HASH_SELECT(dst_hh_name, dst_head, src_hh_name, src_head, condition) HASH_ITER(hh_name, head, item_ptr, tmp_item_ptr) HASH_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
接受單個參數的函數或宏(指向結構的空指針,須要將其強制轉換爲適當的結構類型)。若是應「選擇」結構以將其添加到目標哈希中,則函數或宏的值應爲非零值。
有任何問題,都可經過公告中的二維碼聯繫我