A simple HashMap C language implementation

Source: Internet
Author: User
Tags hash int size key string

Using C language to realize a simple and practical hashmap has certain practical significance. Especially when we don't want to use the Map<...> class in the STL. The HashMap I implement is used to map key---value, the key must be a valid string, and value is any type of data that the caller assigns. This hashmap is suitable to consume very little resources in some simple situations.

First, define the header file as follows:

/*
* 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"

* 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);

/* A 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 (&AMP;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 the 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 is 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 * *

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.