无序集合中的哈希函数
Hash function in an unordered_set
我正在使用一个unordered_set来实现一个哈希表。我不知道如何使用find函数。当我运行这个代码时,我总是遇到seg错误。我知道它是因为find()没有找到元素,但它应该找到。我的问题是,如何将find与我提供的自定义哈希函数一起正确使用?
unordered_set<Play*, Play::Hash> hashedData
unordered_set<Play*>::iterator got;
for (int i = 0; i < 10; ++i) {
got = hashedData.find(data[i]);
cout << (*got)->getSummary() << endl << endl;
}
数据只是
vector<Play*>
我的散列函数看起来像这个
struct Hash {
size_t operator()(Play* const &x) const {
size_t t = 0;
static int hash = 0;
string u = x->getOffense();
string v = x->getDefence();
string w = x->getPlayDesc();
t = u.length() + v.length() + w.length();
t += hash;
++hash;
return t;
}
};
我知道为什么找不到应该找到的元素的根本原因。
您在Hash
函数中使用了静态变量吗
将Hash
函数更改为如下:
struct Hash
{
size_t operator()(Play* const &x) const
{
size_t t = 0;
string u = x->getOffense();
string v = x->getDefence();
string w = x->getPlayDesc();
t = u.length() + v.length() + w.length();
return t;
}
};
此函数有问题,当同一对象A
调用此函数两次时,结果不同。因为您使用了一个静态变量static int hash = 0;
。因此,在您的情况下,当您构造hashedData
时,函数Hash
调用一次,当您使用find
函数时,同一对象再次调用Hash
,但您得到的结果不同,因此函数find
返回hashedData.end()
。
当您调用cout << (*got)->getSummary() << endl << endl;
时,您将遇到seg故障。你应该这样做:
for (int i = 0; i < 10; ++i)
{
got = hashedData.find(data[i]);
if (got != hashedData.end())
{
cout<<(*got)->getSummary()<<endl;
}
}
尝试将您自己的Pred计算器作为第三个参数添加到您的无序集合中。然后,您可以检查正在比较的两个参数。还要验证迭代器在调用find之后是否等于end()。
相关文章:
- 如何为位集找到/实现一个好的哈希函数
- 对于短字符串来说,这是一个很好的哈希函数吗?
- 我在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自定义的哈希函数碰撞