当前位置:网站首页>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;
}
};边栏推荐
猜你喜欢
随机推荐
Bookkeeping APP: Xiaoha Bookkeeping 3 - Production of Login Page
[based] GO language. Why do I have to learn Golang and introduction to the language universal
C language game ------ greedy snake ---- for Xiaobai
【微信小程序】WXSS和全局、页面配置
Go简单实现协程池
轻松学Pytorch-Pytorch可视化
CentOS7安装Oracle数据库的全流程
[WeChat applet] WXSS and global, page configuration
String.split()最详细源码解读及注意事项
The interviewer was stunned by the self-growth of 4 mainstream database IDs in one breath
为什么用了大牌工具后报表开发依然头痛
IO flow: node flow and process flow summarized in detail.
"Pure theory" FPN (Feature Pyramid Network)
JS_删除数组里的无效数据 0 undefined ‘‘ null false NaN
MIT指出公开预训练模型不能乱用
【kaggle】Spaceship Titanic - 预测哪些乘客被运送到另一个维度【CatBoost - 10%】
[Numpy] np.where
Nacos分级存储模型-集群配置与NacosRule负载均衡
[Cloud native] Introduction and use of Feign of microservices
MLX90640 infrared thermal imaging temperature measuring sensor module development notes (9)









