Good hash function for a 2d index(二维索引的良好散列函数)
问题描述
我有一个名为 Point 的结构.要点很简单:
I have a struct called Point. Point is pretty simple:
struct Point
{
Row row;
Column column;
// some other code for addition and subtraction of points is there too
}
Row 和 Column 基本上是美化的 ints,但我厌倦了不小心将输入参数转换为函数并给它们每个包装类.
Row and Column are basically glorified ints, but I got sick of accidentally transposing the input arguments to functions and gave them each a wrapper class.
现在我使用 set 点,但重复查找确实会减慢速度.我想切换到 unordered_set.
Right now I use a set of points, but repeated lookups are really slowing things down. I want to switch to an unordered_set.
所以,我想要一个 Point 的 unordered_set.通常,该集合可能包含例如 80x24 终端上的每个点 = 1920 个点.我需要一个好的散列函数.我只是想出了以下内容:
So, I want to have an unordered_set of Points. Typically this set might contain, for example, every point on a 80x24 terminal = 1920 points. I need a good hash function. I just came up with the following:
struct PointHash : public std::unary_function<Point, std::size_t>
{
result_type operator()(const argument_type& val) const
{
return val.row.value() * 1000 + val.col.value();
}
};
但是,我不确定这是否真的是一个很好的散列函数.我想要一些快速的东西,因为我需要非常快速地进行很多查找.有没有更好的散列函数我可以使用,或者这可以吗?
However, I'm not sure that this is really a good hash function. I wanted something fast, since I need to do many lookups very quickly. Is there a better hash function I can use, or is this OK?
推荐答案
遵循 Effective Java (2nd edition) 中给出的技术,并在 Programming in Scala 中引用了该技术em>.有一个素数常数(我们会说 53,但你可能会发现更大的常数会得到更均匀的分布),并按如下方式执行乘法和加法:
Following the technique is given in Effective Java (2nd edition), and quoted from there in Programming in Scala. Have a prime constant (we'll say 53 but you may find something larger will give more even distribution here), and perform multiplication and addition as follows:
(53 + int_hash(row)) * 53 + int_hash(col)
对于更多值(假设您添加 z 坐标),只需继续嵌套,例如
For more values (say you add a z coordinate), just keep nesting, like
((53 + int_hash(row)) * 53 + int_hash(col)) * 53 + int_hash(z)
其中 int_hash 是用于散列单个整数的函数.您可以访问此页面找到 一堆很好的散列函数用于单个整数.
Where int_hash is a function for hashing a single integer. You can visit this page to find a bunch of good hash functions for single integers.
这篇关于二维索引的良好散列函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:二维索引的良好散列函数
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
