首页 / 软件开发 / C语言 / 一个简单的HashMap C语言实现
一个简单的HashMap C语言实现2010-06-17 csdn博客 张亮用实现一个简单实用的hashmap,具有一定的实际意义。尤其我们不想使用STL里面的map<...>类的时候。我实现的这个hashmap,用来做key---value的映射,key必须是有效的字符串,value是调用者分配的任意类型的数据。这个hashmap适合在一些简单的场合下,消耗极少的资源。首先定义头文件如下:/*
* hashmap.h
* Generic hash map: key(string)-value(any type).
* cheungmine
* Sep. 22, 2007. All rights reserved.
*/
#ifndef HASHMAP_H_INCLUDED
#define HASHMAP_H_INCLUDED
#include "unistd.h"
/* You should always use 1024 */
#define HASHMAP_SIZE 1024
/* Opaque struct pointer to _hash_map_t */
typedef struct _hash_map_t* hash_map;
typedef void(*pfcb_hmap_value_free)(void* value);
/* An example of free value function implemented by caller:
void my_hmap_free_value(void* pv)
{
free(pv);
}
*/
/* Create before use. eg:
* hash_map hm;
* hmap_create (&hm, HASHMAP_SIZE);
* assert (hm); // out of memory if hm==NULL
* void* mydata=malloc(n);
* hmap_insert(hm, "shanghai", -1, mydata);
...
* hmap_destroy(hm, my_hmap_free_value);
*/
extern void
hmap_create(hash_map *hmap, int size);
/* Destroy after use */
extern void
hmap_destroy(hash_map hmap, pfcb_hmap_value_free);
/* Insert a key-value into hash map. value is a pointer to callee-allocated memory */
extern void
hmap_insert(hash_map hmap, const char* key, int key_len/* -1 for strlen to be called */, void* value);
/* Search a hash map for value of given key string */
extern void*
hmap_search(hash_map hmap, const char *key);
#endif /* HASHMAP_H_INCLUDED */