当前位置:网站首页>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;
}
};边栏推荐
- TiCDC Migration - TiDB to MySQL Test
- 【云原生】-Docker容器迁移Oracle到MySQL
- mysql根据多字段分组——group by带两个或多个参数
- [Numpy] 创建数组
- npm install 报错问题解决合集
- Sentinel 2A data preprocessing and calculation of six common vegetation indices in snap software
- mysql数据库安装(详细)
- influxdb2的使用
- 何享健“A拆A”又败一局,美的旗下美智光电终止创业板IPO
- C# 1秒跑一个数字的展示,主要练习 事件相关内容
猜你喜欢
随机推荐
Meta,元宇宙和广告双败的一季
Mysql stored procedures, rounding
MySQL 安装报错的解决方法
Framework common annotation explanation
一口气说出4种主流数据库ID自增长,面试官懵了
conda环境创建及复制
[WeChat applet] WXSS and global, page configuration
如何把Netflix数据集转换成Movielens格式?
Navicat如何连接MySQL
nacos cluster construction
人脸合成效果媲美StyleGAN,而它是个自编码器
html+css+php+mysql实现注册+登录+修改密码(附完整代码)
[Mysql] LENGTH函数
SIP system composition format
C# 1秒跑一个数字的展示,主要练习 事件相关内容
Mysql进阶优化篇01——四万字详解数据库性能分析工具(深入、全面、详细,收藏备用)
bean的生命周期
hash table 实现代码
Chapter ten find and record the REST API
一起来侃个球









