2d(3d) 坐标的哈希图(即双精度向量)?

Den*_*nis 5 c++ hash hashmap c++11

hash map我想知道for 坐标(2d 或 3d,即双精度向量)是否有通用的全能解决方案?

这里的一个例子演示了如何为 创建自定义哈希映射pair<int,int>,但提出从pair<double,double>(可以表示二维坐标)到 的唯一映射似乎并不简单size_t

我知道我可以通过提供比较器对象来使用有序映射,但对于我的应用程序来说,不需要对它们进行排序,而且哈希映射似乎更快。然而,由于我是所有这些东西的新手hash,我有点迷失了如何继续。

p/s/我使用c++11。

And*_*ves 5

为了避免额外的依赖,您可以使用std::hash. 这是一个使用您发布的链接中的代码的示例,并更新为使用std::pair<double,double>

#include <unordered_map>
#include <cassert>

using namespace std;

class TPoint3D{
public:
    TPoint3D(double x, double y, double z) : x(x), y(y), z(z){};

    double x, y, z;
};

struct hashFunc{
    size_t operator()(const TPoint3D &k) const{
    size_t h1 = std::hash<double>()(k.x);
    size_t h2 = std::hash<double>()(k.y);
    size_t h3 = std::hash<double>()(k.z);
    return (h1 ^ (h2 << 1)) ^ h3;
    }
};

struct equalsFunc{
  bool operator()( const TPoint3D& lhs, const TPoint3D& rhs ) const{
    return (lhs.x == rhs.x) && (lhs.y == rhs.y) && (lhs.z == rhs.z);
  }
};

typedef unordered_map<TPoint3D, int, hashFunc, equalsFunc> TPoint3DMap;

int main(){
  TPoint3DMap myMap;

  // test equalsFunc
  myMap[TPoint3D(10.0, 20.0, 30.0)] = 100;
  myMap[TPoint3D(10.0, 20.0, 30.0)] = 200;

  assert(myMap[TPoint3D(10.0, 20.0, 30.0)] == 200);

  // test if hashFunc handles well repeated values inside TPoint3D
  myMap[TPoint3D(10.0, 10.0, 10.0)] = 1;
  myMap[TPoint3D(10.0, 20.0, 10.0)] = 2;
  myMap[TPoint3D(10.0, 10.0, 20.0)] = 3;
  myMap[TPoint3D(20.0, 10.0, 10.0)] = 4;

  assert(myMap[TPoint3D(10.0, 10.0, 10.0)] == 1);
  assert(myMap[TPoint3D(10.0, 20.0, 10.0)] == 2);
  assert(myMap[TPoint3D(10.0, 10.0, 20.0)] == 3);
  assert(myMap[TPoint3D(20.0, 10.0, 10.0)] == 4);

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

正如我之前所说,如果您希望使用其他结构,则必须调整类pairHashpairEquals结构 operator()以分别适当地散列和比较新键。

干杯

编辑 :

  • 修改代码以使用自定义 TPPoint3D 类和统一函子类定义(均使用结构)。
  • 添加了简单的测试来验证哈希和等于函子。