C官方库虽然没有提供map库,但第三方库还是有一些挺不错的,用了几个后发现这些hashmap库对内存有一些要求,而针对STM32这种MCU,内存是最珍贵的资源了,基本都满足不了这些库的要求,就只能自己动手写一个简单粗暴的hashmap库满足自己的需求。
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "hashmap.h"
int main(void)
{
int val[5] = {0, 1, 2, 3, 4};
hashmap* map = HashmapInit(5);
int i=0;
for(;i<5; i++)
{
HashmapPut(map, i, (void*)(val+i));
}
int key = 0;
for(; key<5; key++)
{
int *temp = (int*)HashmapGet(map, key);
printf("%d->%d\n", key, *temp);
}
return 0;
}
#include "hashmap.h"
int HashForInt(hashmap* obj, int key)
{
if(key < 0)
return ((-key)%(obj->size));
return (key%(obj->size));
}
hashmap* HashmapInit(int size)
{
struct _hashmap_table* obj = (struct _hashmap_table*)malloc(sizeof(struct _hashmap_table));
if(obj == NULL)
return NULL;
obj->size = size;
obj->list = (struct _hashmap_node**)calloc(size, sizeof(struct _hashmap_node*));
return obj;
}
void HashmapDestory(hashmap* obj)
{
int i=0;
//循环释放各对键值
for(i=0; i<obj->size; i++)
{
if(obj->list[i] != NULL)
free(obj->list[i]);
}
free(obj->list);
free(obj);
}
void* HashmapPut(hashmap* obj, int key, void *value)
{
int hash=0;
struct _hashmap_node* node=NULL;
if(obj == NULL)
return NULL;
hash = HashForInt(obj, key);
if(obj->list[hash] != NULL)
return NULL;
node = (struct _hashmap_node*)malloc(sizeof(struct _hashmap_node));
if(node == NULL)
return NULL;
node->key = key;
node->value = value;
obj->list[hash] = node;
return (obj->list[hash]);
}
void* HashmapGet(hashmap* obj, int key)
{
int hash = HashForInt(obj, key);
struct _hashmap_node* node = obj->list[hash];
if(node == NULL || node->key != key)
return NULL;
return node->value;
}
#ifndef __HASHMAP_H
#define __HASHMAP_H
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef struct _hashmap_node
{
void* value;
int key;
}hashmap_node;
typedef struct _hashmap_table
{
int size;
struct _hashmap_node** list;
}hashmap;
int HashForInt(hashmap* obj, int key);
hashmap* HashmapInit(int size);
void HashmapDestory(hashmap* obj);
void* HashmapPut(hashmap* obj, int key, void *value);
void* HashmapGet(hashmap* obj, int key);
#endif //__HASHMAP_H