当前位置:网站首页>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;
}
};边栏推荐
- 拦截器与过滤器(三)@interface自定义注解拦截
- 如何监控海外服务器性能
- 38.【string下章】
- The meaning of "last in first out" in stack and "first in first out" in queue
- IDEA2021.2安装与配置(持续更新)
- Mysql stored procedures, rounding
- 【kaggle】Spaceship Titanic - 预测哪些乘客被运送到另一个维度【CatBoost - 10%】
- 如何把Netflix数据集转换成Movielens格式?
- IO flow: node flow and process flow summarized in detail.
- [WeChat applet] One article to solve button, input, image components
猜你喜欢

BGP简单实验
![[based] GO language. Why do I have to learn Golang and introduction to the language universal](/img/ac/80ab67505f7df52d92a206bc3dd50e.png)
[based] GO language. Why do I have to learn Golang and introduction to the language universal

Sql文件导入数据库-保姆级教程

DVWA full level customs clearance tutorial

IO流:节点流和处理流详细归纳。

MySQL八股文背诵版

命里有时终须有--记与TiDB的一次次擦肩而过

The interviewer was stunned by the self-growth of 4 mainstream database IDs in one breath

一起来侃个球

如何把Netflix数据集转换成Movielens格式?
随机推荐
Container is changed | deploy MySQL cluster in the Rancher
投资127亿!深圳,再添一所985
Bika LIMS 开源LIMS集—— SENAITE的使用(用户、角色、部门)
TiFlash 源码阅读(五) DeltaTree 存储引擎设计及实现分析 - Part 2
MySQL database installation (detailed)
SIP system composition format
piglit_get_gl_enum_name 参数遍历
pycharm专业版使用
JS_删除数组里的无效数据 0 undefined ‘‘ null false NaN
[Mysql] LENGTH函数
MySQL 安装报错的解决方法
Dataset:Medical Data and Hospital Readmissions医疗数据和医院再入院情况数据集的简介、下载、使用方法之详细攻略
mysql根据多字段分组——group by带两个或多个参数
mysql5.7.35安装配置教程【超级详细安装教程】
MySQL八股文背诵版
[WeChat applet] One article to solve button, input, image components
阿里云官方 Redis 开发规范!
IO flow: node flow and process flow summarized in detail.
记账APP:小哈记账3——登录页面的制作
mongo根据时间字段进行时间格式化并进行统计