0

I'm looking for a way to use a std::unordered_map using a 2D point for the key.

My original plan was simply:

unordered_map<glm::ivec2, int> map

but it seems that isn't available. Is there a 2D type that would work with unordered_map?

Nick
  • 463
  • 4
  • 13

1 Answers1

3

std::unordered_map is a hashmap. By the properties of a hashmap to use a type as the key, there must be a hash and equals function defined for that type. By default std::unordered_map uses std::hash and std::equal_to for that purposes.

The simple solution:

Luckily for you these appear to be already defined in glm/gtx/hash.hpp just include it before unordered_map. (See: https://github.com/g-truc/glm/blob/master/glm/gtx/hash.hpp)

The complex solution:

If those are not defined for a type, then you can use custom functions by overloading the template. This would look something like:

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;
Jarra McIntyre
  • 1,265
  • 8
  • 13