我需要一个用于 3D vector 的散列函数,并且关闭键值之间没有冲突。
key 是一个 3d 整数 vector 。我希望在大约 64 * 64 * 64“区域”或更大的“区域”内没有碰撞。
有没有人知道任何适用于此目的的哈希函数,或者更好的是,您将如何为此设计哈希?
如果有必要知道,我会用 C++ 实现它。
最佳答案
为什么不创建一个 Map<int,Map<int,Map<int,Object>>>
为你的对象?每个int
是 x、y、z 或您标记轴的任何内容。
这是一个如何使用它的示例。
int x,y,z;
map<int,map<int,map<int,string>>> Vectors = map<int,map<int,map<int,string>>>();
/*give x, y and z a real value*/
Vectors[x][y][z] = "value";
/*more code*/
string ValueAtXYZ = Vectors[x][y][z];
只是为了解释,因为它不是很明显。
Vectors[x]
返回 map<int,map<int,string>>
.
然后我立即使用该 map []
运算符 [y]
.
然后返回(你猜对了)一个 map<int,string>
.
我立即使用那个 map []
运算符 [z]
现在可以设置字符串了。
注意:请务必使用迭代而不是 for(int x = 0; /*bad code*/;x++)
遍历它循环因为 []
在它用于查找的每个位置添加一个元素。 Here's循环示例和 Here's以及意外添加的示例。
编辑:
如果您想确保您没有覆盖现有值,您可以这样做。
string saveOldValue;
if(Vectors[x][y][z] != ""/*this is the default value of a string*/)
{
/*There was a string in that vector so store the old Value*/
saveOldValue = Vectors[x][y][z];
}
Vectors[x][y][z] = "Value";
如果您使用 []
在不在 map 中的键上, map 会在那里创建一个默认对象。对于字符串,这将是空字符串 ""
.
或者
if( Vectors.find(x)!=Vectors.end()
&& Vectors[x].find(y)!=Vectors[x].end()
&& Vectors[x][y].find(z)!=Vectors[x][y].end())
{
/* Vectors[x][y][z] has something in it*/
}else
{
/*Theres nothing at Vectors[x][y][z] so go for it*/
Vectors[x][y][z] ="value";
}
这使用了 find(value)
返回指向键“值”OR 位置的迭代器和指向 map::end()
的迭代器的函数如果该键不在当前 map 中。
如果您没有为要存储的东西设置默认值,则使用第二个检查来进行插入。这大大提高了这个答案的可用性,并使您的代码更加整洁。
insert
函数有它的位置,但在这个例子中它会很难使用。
关于c++ - 接近值无冲突的 3D 哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22950208/