【问题标题】:3D Hash with no collisions on close values3D 散列,接近值没有冲突
【发布时间】:2014-05-21 22:14:29
【问题描述】:

我需要一个用于 3D 向量的散列函数,并且关闭键值之间没有冲突。

关键是整数的 3d 向量。我希望在大约 64 * 64 * 64 或更大的“区域”内没有碰撞。

有谁知道适合此目的的任何散列函数,或者更好的是,您将如何为此设计散列?

如果有必要知道,我会用 C++ 实现。

【问题讨论】:

  • 为什么不为您的对象创建一个Map<int,Map<int,Map<int,Object>>>?其中每个 int 是 x、y、z 或您标记轴的任何内容。如果需要浮点值,或者使用 double
  • 不错的解决方案,但它会导致一些相当复杂的代码 - 这就是插入元素的方式: auto it1 = map.insert(std::make_pair(x, std::unordered_map>())).first; auto it2 = it1->second.insert(std::make_pair(y, std::unordered_map())).first; it2->second.insert(std::make_pair(z, Object()));
  • 我会以不同的方式检查我添加的答案。

标签: c++ vector hash 3d collision


【解决方案1】:

为什么不为您的对象创建一个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&lt;int,map&lt;int,string&gt;&gt;

然后我立即使用映射[] 运算符和[y]

然后返回(你猜对了)map&lt;int,string&gt;

我立即使用映射[] 运算符和[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";

如果您在不在地图中的键上使用[],则地图会在那里创建一个默认对象。对于字符串,这将是空字符串""

或者

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()

如果您没有存储的东西的默认值,则使用第二个检查来进行插入。这极大地增加了此答案的可用性并整理了您的代码。

insert 函数有它的位置,但在这个例子中它很难使用。

【讨论】:

  • 除非我仍然使用insert,因为在我的情况下,如果它已经存在,我不想覆盖它。
  • @Brett 检查我刚刚添加的编辑我认为它会让你的生活更轻松。
猜你喜欢
  • 1970-01-01
  • 2020-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-28
  • 2012-01-01
相关资源
最近更新 更多