用户定义无序映射的哈希函数
User defined hash function for unordered map
我已经为一个unorderd_map定义了我自己的哈希函数。但我无法使用查找函数在容器中搜索。我尝试过在哈希函数中使用打印语句进行调试,它生成了插入键/值时生成的相同哈希值。如果有人能指出这个错误就太好了。我在windows上使用Eclipse IDE,我正在编译-std=c++11
typedef struct tree node;
struct tree
{
int id;
node *left;
node *right;
};
class OwnHash
{
public:
std::size_t operator() (const node *c) const
{
cout << "Inside_OwnHash: " <<std::hash<int>()(c->id) + std::hash<node *>()(c->left) + std::hash<node *>()(c->right) << endl;
return std::hash<int>()(c->id) + std::hash<node *>()(c->left) + std::hash<node *>()(c->right);
}
};
int main()
{
std::unordered_map<node *,node *,OwnHash> ut;
node * one = new node;
one->id = -1;
one->left = nullptr;
one->right = nullptr;
ut.insert({one,one});
node * zero = new node;
zero->id = 0;
zero->left = NULL;
zero->right = NULL;
ut.insert({zero,zero});
node * cur = new node;
cur->id = 5;
cur->left = zero;
cur->right = one;
ut.insert({cur,cur});
for (auto& elem : ut)
{
std::cout << "key: " << elem.first << "t" << "value: " << elem.second->id << std::endl;
}
node * parse = new node;
parse->id = 5;
parse->left = zero;
parse->right = one;
std::unordered_map<node *,node *>::const_iterator got1 = ut.find (parse);
if ( got1 == ut.end() )
std::cout << "not found";
else
std::cout << got1->first << " is " << got1->second->id << std::endl;
return EXIT_SUCCESS;
}
Output:
Inside_OwnHash: 4294967295
Inside_OwnHash: 0
Inside_OwnHash: 22946517
key: 0xaf11b0 value: 5
key: 0xaf1180 value: 0
key: 0xaf1150 value: -1
Inside_OwnHash: 22946517
not found
哈希是不够的,你还必须实现相等比较!
哈希必须是这样一个函数:如果项相等,则它们的哈希值相等。但是,由于项目可能是任意复杂的,并且哈希结果只是size_t,因此相反的含义不成立,也不能成立。因此,要找到确切的元素,还需要进行相等比较。
查找时,哈希函数指向正确的"桶",但其中可能有多个元素,或者其中可能有一个元素,但不是您要查找的那个。因此,它获取bucket中的所有元素,并将每个元素与您正在搜索的元素进行比较。
现在您提供了一个散列函数,但没有提供相等比较器。所以它使用默认值,也就是operator==
,那是用来比较地址的指针。地址不等于。您需要提供相等函子来比较值
相关文章:
- 如何为位集找到/实现一个好的哈希函数
- 对于短字符串来说,这是一个很好的哈希函数吗?
- 我在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自定义的哈希函数碰撞