当前位置:网站首页>Hash table implementation code
Hash table implementation code
2022-07-29 13:31:00 【The rookie's road to artificial intelligence】
C++代码中有unodered_map<>()可实现hash操作,But in code that pursues efficiency,Use will seriously affect the execution efficiency of the code.
Usually implemented manuallyhash tableEfficiency will be greatly improved,This is crucial for the pursuit of extreme efficiency.
通常的hashOperations have string hashes and hashes of larger data.
- 字符串哈希,Usually a shift operation is used.hval = hval << 5 + (str[i] - 'a' + 1),同时需要将 hval 进行缩放,Generally correct here13131(larger prime number,Experiments have found that hash collisions are small)或者2的次方(CPUFor when calculating division2The power of the speed is faster)取余.
- Hash for larger data,Generally correct13131或者2The square of the remainder.(这其实也就是hash table的范围)
#define HASHSIZE 10
#define ull unsigned long long
typedef unsigned int uint;
typedef struct Node {
const char* key;
const char* value;
Node* next;
}Node;
struct HashTable {
Node* node[HASHSIZE];
void clear() {
for (int i = 0; i < HASHSIZE; ++i)
node[i] = nullptr;
}
uint hash(const char* key) {
ull res(0);
int i = 0;
while (key[i] != '\0') {
res = res << 5 + (key[i] - 'a' + 1);
++i;
}
return res % HASHSIZE;
}
Node* lookup(const char* key) {
Node* np;
uint index = hash(key);
for (np = node[index]; np; np = np->next)
if (!strcmp(key, np->key))
return np;
return nullptr;
}
bool install(const char* key, const char* value) {
uint index;
Node* np;
if (!(np == lookup(key))) {
index = hash(key);
np = (Node*)malloc(sizeof(Node));
if (!np) return false;
np->key = key; np->next = node[index];
node[index] = np;
}
np->value = value;
return true;
}
};
边栏推荐
猜你喜欢
随机推荐
Chapter 6 c + + primer notes 】 【 function
学习的时候碰见的一个sql问题,希望大佬们可以解答一二?
连接oracle数据库指令
【C#】WCF和TCP消息通信练习,实现聊天功能
A recent paper summarizes
Legendary version adds npc modification, adds npc method and configuration parameter tutorial
一口气说出4种主流数据库ID自增长,面试官懵了
一起来侃个球
3D激光SLAM:LeGO-LOAM论文解读---硬件系统部分
获取list集合中重复的元素
Container is changed | deploy MySQL cluster in the Rancher
常坐飞机的你,为什么老惦记着“升舱”?
snap软件中哨兵2A数据预处理及六种常用植被指数的计算
MySQL常用的日期时间函数
MySQL 视图(详解)
kotlin协程与线程池
DVWA full level customs clearance tutorial
Py之eli5:eli5库的简介、安装、使用方法之详细攻略
Mysql各个大版本之间的区别
The torch using summary