返回错误值的双哈希函数
Double hashing function returning wrong value
我正在创建一个双哈希图,但插入后删除功能不起作用。我遵循相同的格式来增加索引,但它只是没有达到正确的索引。
class RHHM {
unsigned int hash2( int key ) {
return key % (M-1) + 1;
}
//Private variables
hashNode ** map; //Backing array
unsigned int M; //Capacity of array
//If index that key hashes to is empty, insert. Else, replace value at hashed index.
int insert( int key, char value ) {
int f = hash( key );
int f2 = hash2 ( key );
int p = 0;
int h = f + (p * f2) % M;
while( map[h] != NULL ) {
if( p == M )
return -1 * p;
if( map[h]->key == key ) {
map[h]->value = value;
return p;
}
else {
++p;
h = f + (p * f2) % M;
}
}
map[h] = new hashNode( key, value );
return p;
}
int remove( int key, char &value) {
int f = hash( key );
int f2 = hash2 ( key );
int p = 0; //Keeps track of how many indexes have been checked
int h = f + (p * f2) % M;
while( map[h] != NULL ) {
if( p == M ) //If item is not found in table, return false
return -1 * p;
if( key == map[h]->key ) //If key is found, break out of loop
break;
else {
++p;
h = f + (p * f2) % M; //Wrap around array if necessary
}
}
if( map[h] == NULL ) //If end of cluster reached, return false
return -1 * p;
value = map[h]->value; //Stores the value of the item to be deleted
delete map[h]; //Delete the item the user specified
map[h] = NULL;
++p;
h = f + (p * f2) % M;
for( ; map[h] != NULL; h = f + (p * f2) % M) { //While still in the cluster, remove and reinsert all items
int tempKey = map[h]->key;
char tempValue = map[h]->value;
delete map[h];
map[h] = NULL;
insert(tempKey, tempValue);
++p;
}
return p;
}
}
这是我的主要内容:
RHHM bh(10);
bh.insert(0, 'A');
bh.insert(10, 'B');
bh.insert(20, 'C');
bh.print(std::cout);
输出:
<[ 0:A, - , 10:B, 20:C, - , - , - , - , - , - ]>
如您所见,第一个索引哈希为 0
。由于10
键与0
冲突,双哈希(10
)应该哈希到1
,但它的哈希到2
。为什么它返回错误的值?
这是因为 hash2 函数为键 10 返回值 2。对于 hash2(10),hash2 可以显示为。
return 10 % (10-1) + 1
这反过来又通过运算符优先级计算到值 2 AS。
return (10 %(10-1))+1
在插入函数中,当发生冲突时,您将 hash2 值添加到哈希值以获得计算为 的新索引。
h= f + ( P * f2 ) % M
h= 0 + (1 * 2 ) % 10 \ this evaluates to 2.
这就是将新索引设置为 2 的原因。
编辑:代码解决了运算符优先级的一些问题。第一 h = f + (p * f2) % M; 必要时环绕阵列
这不会环绕数组。 因为 % 的优先级高于 +。 f 的值在范围 [0-M-1] 中,(p *f2) % M 的值在范围 [0-M-1] 中。因此,上述表达式的计算结果可能为 [0-2*M-2] 范围内的值。这适用于代码中的其他此类表达式。这是哈希表中可能缺少某些键的原因。
相关文章:
- 如何为位集找到/实现一个好的哈希函数
- 对于短字符串来说,这是一个很好的哈希函数吗?
- 我在C++中使用提升哈希函数将 3 个双精度组合成一个面临冲突的哈希
- 无冲突的哈希函数
- Qt5 哈希函数在 Windows 7 和 Windows10 上不会返回相同的哈希
- 解决由于在哈希函数中使用了不完整的类型而导致的编译失败
- 使用 Murmur2 64 位哈希函数生成会导致冲突的输入
- 错误:哈希函数必须可使用键类型的参数进行调用
- unordered_set是否适合存储矢量<int>元素的数据结构?如果是这样,我将如何实现哈希函数?
- 为什么C++哈希函数的返回类型是 std::size_t,而不是独立于平台的类型?
- 哈希函数计算
- 哈希函数中同一键的不同值和良好的哈希值排序
- 将 C# 哈希函数转换为C++
- 如何创建用于生成噪声的哈希函数
- 插入不从哈希函数中检索键
- 简单的 C++11 哈希函数无法编译
- 对于这个英语单词列表来说,什么是好的哈希函数?
- std::bitset 哈希函数算法
- 如何生成伪随机 32 字节字符串以用作加密哈希函数中的盐?
- C unordered_map自定义的哈希函数碰撞