C語言雜湊表的實現

2021-10-01 03:41:19 字數 3303 閱讀 4122

寫這個hashmap的最初目的是在微控制器上使用,後來就著學習的態度自己就把他完善了一下,hashmap的大小、key的最大長度、value的最大長度都是在標頭檔案中通過巨集定義配置。

完整**使用到了:

完整**:

//

// created by ankun on 2019/12/3.

//#ifndef myhashmap_hashmap_h

#define myhashmap_hashmap_h

#include

#include

#include

#include

#include

"malloc.h"

#include

"list.h"

#define hmalloc mem_malloc

#define hfree mem_free

#define hmemcpy mem_memcpy

#define hmemset mem_memset

#define hrealloc mem_realloc

#define key_max_len 16

// key的最大長度

#define val_max_len 32

// value的最大長度

#pragma pack(4)

typedef

struct list_head hashtable;

typedef

struct

hashmap;

typedef

struct

entry;

hashmap *

hashmap_create

(uint32_t size)

;void

hashmap_destroy

(hashmap *hashmap)

;bool hashmap_put

(hashmap *hashmap,

const

void

*key,

const

void

*value)

;void

*hashmap_get

(const hashmap *

const hashmap,

const

void

*key)

;void

hashmap_clear

(hashmap *hashmap)

;void

hashmap_remove

(hashmap *hashmap,

const

void

*key)

;bool hashmap_exists

(const hashmap *

const hashmap,

const

void

*key)

;void

hashmap_getkeys

(const hashmap *

const hashmap, uint8_t *

*keys, uint32_t *count)

;#pragma pack()

#endif

//myhashmap_hashmap_h

#include

#include

"hashmap.h"

#define put(key, value) hashmap_put(hashmap, key, value)

#define get(key) hashmap_get(hashmap, key)

#define getkesy(keys, count) hashmap_getkeys(hashmap, keys, count)

#define remove(key) hashmap_remove(hashmap, key)

#define clear() hashmap_clear(hashmap)

#define exists(key) hashmap_exists(hashmap, key)

intmain()

,,};

const

unsigned

int npair =

sizeof

(pairs)

/sizeof

(pairs[0]

);// 初始化自建記憶體池

mem_init()

;// 建立hashmap

hashmap *hashmap =

hashmap_create(10

);// 加入和獲取

for(

int i =

0; i != npair; i++

)printf

("\r\n");

// 檢視記憶體池資訊

printf

("memory: \r\n"

,mem_perused()

,mem_getused()

,mem_getfree()

);// 獲取所有key

int count =0;

uint8_t *keys[10]

;getkesy

(keys,

&count)

;for

(int j =

0; j < count;

++j)

printf

("\r\n");

// 刪除

remove

("key1");

// 檢測是否存在

bool i***ists =

exists

("key1");

printf

("%s\r\n"

, i***ists ?

"true"

:"false");

// 清空

clear()

;// 銷毀hashmap

hashmap_destroy

(hashmap)

;// 檢視記憶體池資訊

printf

("memory: \r\n"

,mem_perused()

,mem_getused()

,mem_getfree()

);return0;

}

ends…

雜湊表 雜湊表 C語言簡單實現

本文參考自 大話資料結構 通過某個函式f計算出記錄的儲存位置,而不需要通過比較,這就是一種新的儲存技術 雜湊技術。雜湊技術是在記錄的儲存位置和它的關鍵字之間建立乙個確定的對應關係f,使得每個關鍵字key對應乙個儲存位置f key 在查詢時,根據這個確定的對應關係找到給定值key的對映f key 若查...

雜湊表 C語言實現

這裡不講高深理論,只說直觀感受。雜湊表的目的就是為了根據資料的部分內容 關鍵字 直接計算出存放完整資料的記憶體位址。void list find by key list,key return p 為了解決根據關鍵字快速找到元素的存放位址,雜湊表應運而生。它通過某種演算法 雜湊函式 直接根據關鍵字計算...

c語言實現雜湊表

雜湊表大家都在資料結構中學習過,應該是查詢最快的一種資料結構了,最好的情況下可以達到線性的時間複雜度。鍵key的狀態碼如果為 vt undefined 的話那麼就是這個槽位沒有被占用或者已經被刪除了 值value的狀態碼有vt true和vt false兩種,只要這個槽位已經被占用過了,那麼valu...