C++ Map(list与数组的结合char型)(hash算法.)

来源:互联网 发布:淘宝客服怎么做好 编辑:程序博客网 时间:2024/06/04 06:23

//注意char类型的map是需要用字符串判断所get的key是否与存储的key相等的,所以不再是map->key == key;这里要注意,还有,一开始我做的时候不明白为什么hash要*33,后来明白,其实是冲突防止会分布不均匀,因为hash需要的就是提高效率,所以*33拉开距离,使得存储尽可能的均匀,当然因为所得数字肯定是会很大的,所以还是一样用了hash的取余法再次进行取余分配到1024数组中。微笑




.c文件


#ifndef __MAP_H__
#define __MAP_H__
#include "typedef.h"


typedef struct MapItem  MapItem;
typedef struct Map  Map;


struct MapItem{
MapItem* next;
void* value;
char* key;
};


struct Map{
MapItem* mArr[1024];
};

my_extern void MapInit(Map* map);
my_extern void MapSet(Map* map, char* key, void* value);
my_extern void* MapGet(Map* map, char* key);
my_extern int my_strcmp(const char* str1, const char* str2);
my_extern unsigned int Hash33(char *str);
my_extern char* strCopy(char* str);

#endif




.h文件

#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, char* key, void* value){
MapItem* p;

int strKey = Hash33(strCopy(key));
p = (MapItem*)malloc(sizeof(MapItem));

if (map->mArr[strKey % 1024] == NULL)

map->mArr[strKey % 1024] = p;
p->key = key;
p->value = value;
p->next = NULL;
}
else
{
p->next = map->mArr[strKey % 1024];
map->mArr[strKey % 1024] = p;
p->key = key;
p->value = value;
}
}


void* MapGet(Map* map, char* key){
MapItem* p;
int strKey = Hash33(strCopy(key));
p = map->mArr[strKey % 1024];
while (p != NULL)
{
if (my_strcmp(p->key,key)==0)
{
return p->value;

p = p->next;
}
return 0;
}
char* strCopy(char* str){
int keyNum = strlen(str) + 1;
char *keyHash = (char*)malloc(keyNum);
char *keyHash2 = keyHash;
while (*str != '\0')
{
*keyHash++ = *str++;
printf("%s", keyHash2);
}
*keyHash = '\0';
printf("%s", keyHash2);
return keyHash2;
}

unsigned int Hash33(char *str)
{
unsigned int hash = 0;
while (*str)
{
hash = hash*33 + (*str++);
}
return hash;
}
int my_strcmp(const char* str1, const char* str2){
while (*str1 != '\0' || *str2 != '\0')
{
if (*str1 == *str2)
{
*str1++;
*str2++;
continue;
}
else if (*str1 < *str2)
{
*str1++;
*str2++;
return -1;
}
else if (*str1 > *str2)
{
*str1++;
*str2++;
return 1;
}
}
return 0;
}

0 0
原创粉丝点击