当前位置:网站首页>hash table 实现代码
hash table 实现代码
2022-07-29 12:44:00 【菜鸟的人工智能之路】
C++代码中有unodered_map<>()可实现hash操作,但是在追求效率的代码中,使用会严重影响代码的执行效率。
通常使用自己手动实现的hash table效率会有大幅度的提升,这对于追求极致效率的题目至关重要。
通常的hash操作有字符串哈希和较大数据的哈希。
- 字符串哈希,通常利用移位操作。hval = hval << 5 + (str[i] - 'a' + 1),同时需要将 hval 进行缩放,这里一般可以对13131(较大的质数,实验发现哈希冲突较小)或者2的次方(CPU计算除法时对于2的次方速度较快)取余。
- 对较大的数据哈希,一般也是对13131或者2的次方取余。(这其实也就是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;
}
};边栏推荐
猜你喜欢

BGP简单实验

How Navicat Connects to MySQL
![[WeChat applet] WXSS and global, page configuration](/img/ff/fe4c827bc887b8afefa72dc9b230af.jpg)
[WeChat applet] WXSS and global, page configuration

2022年编程语言排名,官方数据来了,让人大开眼界

图解 Attention(完整版)!

【云原生】-Docker容器迁移Oracle到MySQL
![[纯理论] FPN (Feature Pyramid Network)](/img/30/cfb6e3197bc2f4e7e0f1d492976c47.png)
[纯理论] FPN (Feature Pyramid Network)

38.【string下章】

DVWA full level customs clearance tutorial

MySql string splitting realizes the split function (field splitting, column switching, row switching)
随机推荐
PD 源码分析- Checker: region 健康卫士
TiDB upgrade share with case (TiDB v4.0.1 to v5.4.1)
js进阶四(map、reduce、filter、sort、箭头函数、class继承、yield)
我和 TiDB 的故事 | TiDB 对我不离不弃,我亦如此
2022 IDEA (学生邮箱认证)安装使用教程以及基础配置教程
Wu En 07 regularization of teacher machine learning course notes
【C#】WCF和TCP消息通信练习,实现聊天功能
常坐飞机的你,为什么老惦记着“升舱”?
mysql5.7.35安装配置教程【超级详细安装教程】
Interceptors and filters (3) @interface custom annotation interception
TiCDC Migration - TiDB to MySQL Test
TiDB升级与案例分享(TiDB v4.0.1 → v5.4.1)
Dataset:Medical Data and Hospital Readmissions医疗数据和医院再入院情况数据集的简介、下载、使用方法之详细攻略
[纯理论] FCOS
[WeChat applet] One article to solve button, input, image components
投资127亿!深圳,再添一所985
sleep()方法和wait()方法的区别?安全
asyncawait和promise的区别
容器化 | 在 Rancher 中部署 MySQL 集群
【微信小程序】一文解决button、input、image组件