如何在 C 0x 中组合哈希值?

新手上路,请多包涵

C++0x 增加了 hash<...>(...)

我找不到 hash_combine 函数,如 boost 中所述。实现这样的事情的最干净的方法是什么?也许,使用 C++0x xor_combine

原文由 Neil G 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 601
2 个回答

好吧,就像助推器那样做:

 template <class T>
inline void hash_combine(std::size_t& seed, const T& v)
{
    std::hash<T> hasher;
    seed ^= hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2);
}

原文由 Karl von Moor 发布,翻译遵循 CC BY-SA 2.5 许可协议

您可以使用我开发的 第一个 C++ 库来执行此操作:

 #include "rst/stl/hash.h"

struct Point {
  Point(const int x, const int y) : x(x), y(y) {}

  int x = 0;
  int y = 0;
};

bool operator==(const Point lhs, const Point rhs) {
  return (lhs.x == rhs.x) && (lhs.y == rhs.y);
}

namespace std {

template <>
struct hash<Point> {
  size_t operator()(const Point point) const {
    return rst::HashCombine({point.x, point.y});
  }
};

}

原文由 Sergey Abbakumov 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题