c_cpp STM32 C简单粗暴的散列映射hashmap
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp STM32 C简单粗暴的散列映射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
以上是关于c_cpp STM32 C简单粗暴的散列映射hashmap的主要内容,如果未能解决你的问题,请参考以下文章
散列表(has table哈希表)
散列表的概念及其拉链法和常见的散列函数(C语言)
[笔记]为啥hashmap查询速度快? 如何理解hashmap的散列?
c_cpp 发送临时和卷STM32。
c_cpp STM32 led灯光测试
c_cpp STM32F103超频