C++ Map(list与数组的结合int型)(hash算法.)
2016-04-10 19:15
926 查看
不知道怎么解释,也懒得敲那么多废话,直接贴代码了!
.h文件
#ifndef __MAP_H__
#define __MAP_H__
#include "typedef.h"
typedef struct MapItem MapItem;
typedef struct Map Map;
struct MapItem{
MapItem* next;
void* value;
int key;
};
struct Map{
MapItem* mArr[1024];
};
my_extern void MapInit(Map* map);
my_extern void MapRelease(Map* map);
my_extern void MapSet(Map* map, int key, void* value);
my_extern void* MapGet(Map* map, int key);
#endif
.c文件
#include "Map.h"
#include "stdafx.h"
#include <stdlib.h>
#include "string.h"
void MapInit(Map* map){
int i = 1024;
while (i>=0 )
{
--i;
map->mArr[i] = NULL;
}
}
void MapSet(Map* map, int key, void* value){
MapItem* p;
p = (MapItem*)malloc(sizeof(MapItem));
if (map->mArr[key % 1024] == NULL)
{
map->mArr[key % 1024] = p;
p->key = key;
p->value = value;
p->next = NULL;
}
else
{
p->next = map->mArr[key % 1024];
map->mArr[key % 1024] = p;
p->key = key;
p->value = value;
}
}
void* MapGet(Map* map, int key){
MapItem* p;
p = map->mArr[key % 1024];
while (p != NULL)
{
if (p->key == key)
{
return p->value;
}
p = p->next;
}
return 0;
}
.h文件
#ifndef __MAP_H__
#define __MAP_H__
#include "typedef.h"
typedef struct MapItem MapItem;
typedef struct Map Map;
struct MapItem{
MapItem* next;
void* value;
int key;
};
struct Map{
MapItem* mArr[1024];
};
my_extern void MapInit(Map* map);
my_extern void MapRelease(Map* map);
my_extern void MapSet(Map* map, int key, void* value);
my_extern void* MapGet(Map* map, int key);
#endif
.c文件
#include "Map.h"
#include "stdafx.h"
#include <stdlib.h>
#include "string.h"
void MapInit(Map* map){
int i = 1024;
while (i>=0 )
{
--i;
map->mArr[i] = NULL;
}
}
void MapSet(Map* map, int key, void* value){
MapItem* p;
p = (MapItem*)malloc(sizeof(MapItem));
if (map->mArr[key % 1024] == NULL)
{
map->mArr[key % 1024] = p;
p->key = key;
p->value = value;
p->next = NULL;
}
else
{
p->next = map->mArr[key % 1024];
map->mArr[key % 1024] = p;
p->key = key;
p->value = value;
}
}
void* MapGet(Map* map, int key){
MapItem* p;
p = map->mArr[key % 1024];
while (p != NULL)
{
if (p->key == key)
{
return p->value;
}
p = p->next;
}
return 0;
}
相关文章推荐