使用2D点进行查找的Unordered_map

时间:2018-07-07 22:12:36

标签: c++ c++11

我正在寻找一种使用std :: unordered_map并使用2D点作为键的方法。

我最初的计划很简单:

unordered_map<glm::ivec2, int> map

,但似乎不可用。是否有2D类型可以与unordered_map一起使用?

1 个答案:

答案 0 :(得分:2)

std::unordered_map是一个哈希图。通过将类型用作键的哈希图的属性,必须为该类型定义一个哈希和等于函数。默认情况下,std::unordered_map为此使用std::hashstd::equal_to

简单的解决方案:

幸运的是,这些似乎已经在glm/gtx/hash.hpp中定义了,只需将其包括在unordered_map之前。 (请参阅:https://github.com/g-truc/glm/blob/master/glm/gtx/hash.hpp

复杂的解决方案:

如果未为类型定义这些功能,则可以通过重载模板来使用自定义功能。看起来像这样:

struct IVec2Hash {
   std::size_t operator()(const glm::ivec2 &v) const { /* implementation goes here */ }
};

struct IVec2Equals {
  bool operator()(const glm::ivec2 &a, const glm::vec2 &b) const { /* implementation */ }
};

std::unordered_map<glm::ivec2, int, IVec2Hash, IVec2Equals> ivec2_umap;