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;
}
- C++ Map(list与数组的结合char型)(hash算法.)
- C++ Map(list与数组的结合int型)(hash算法.)
- Map与List结合而成的强大的数据结构
- 关于Map集合与List集合的结合
- gsp进行遍历map与list的结合
- char指针与char数组的区别(非常详细!)
- char指针与char数组的区别(非常详细!)
- char指针与char数组的区别(非常详细!)
- char指针与char数组的区别(非常详细!)
- 算法 哈希(hash——map)
- fastjson与Map、List结合使用
- 关于Hash Map的工作原理与面试题的结合讨论
- 查找(三)hash 与map
- Map和List的对象是否是同一对象(并说明hash冲突)
- c语言==字符数组与字符串,char的取值范围(1)
- 结合redis设计与实现的redis源码学习-24-二进制位数组(Bitops.c)
- list set map的遍历(数组等复习)
- HASH 与MAP 的区别
- 操作系统
- POJ 1852 Ants
- HTTP 411 Content-Length required
- 蓝桥杯java -身份证号码升级
- 关于Java流的方式将数据写入到文件中
- C++ Map(list与数组的结合char型)(hash算法.)
- android中自定义组合组件(一)
- Qt浅谈之五十界面自定义
- 使用HttpURLConnection向服务器发送post和get请求
- String、StringBuffer与StringBuilder之间区别
- 学习进程:第二章2.9jsp脚本的9个内置对象
- python的数据类型
- iOS多线程开发系列之(三)Grand Central Dispatch(GCD)
- 去掉SQL数据库里重复的数据,并保留一条