c++ - 一对碰撞几率很低的整数的最小哈希函数是什么?

标签 c++ hash

这是我目前所拥有的:

struct pairhash {
public:
  inline std::size_t operator()(const std::pair<int, int> &c) const
  {
     int x = c.first;
     int y = c.second;
     return ((x+y)*(x+y+1)/2 + y); // Cantor's enumeration of pairs
  }
};

我需要使用这个哈希函数,这样我就可以像这样将这对整数放入 unordered_set 中:

std::unordered_set< std::pair<int, int>,  pairhash> mySet;

编辑:忘记从这对中获取坐标。更新了代码。 编辑:删除了模板代码 - 错误地添加了它。

编辑:根据 SO 上的另一个类似答案更改了函数,与 Cantor 的对枚举相关: hash function providing unique uint from an integer coordinate pair

编辑:无碰撞不是必需的(感谢 Petr)。

最佳答案

如果您打算将它与unordered_set 一起使用,则不需要哈希函数是无冲突的。 (以及大多数其他容器和算法)。此外,哈希表和哈希函数的一般概念是它们允许冲突,它们只是希望冲突很少发生。

cppreference says about the requirements for hashing :

  1. For two different parameters k1 and k2 that are not equal, the probability that std::hash<Key>()(k1) == std::hash<Key>()(k2) should be very small, approaching 1.0/std::numeric_limits<size_t>::max().

关于c++ - 一对碰撞几率很低的整数的最小哈希函数是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37918951/

相关文章:

algorithm - 从哈希到排列

c++ - 将 char 分配给 int 变量时的奇怪行为

c++ - 在 netbeans 7.2 mac os x 上激活 C++ 11

c++ - 在 Ncurses 上添加一个滚动条或者让它像 "more"

每个 3 个值的数据集的 Ruby 解决方案

json - 如何在 Perl 中将简单的哈希转换为 json?

security - 为什么 SHA-1 哈希函数的最大消息大小 (2^64) - 1 位?

c++ - OpenCV 3.0 上的 GPU 功能在哪里?

c++ - 链接/编译使用 boost/filesystem.hpp 的程序

python - 为什么 Python 哈希函数在 Android 实现上运行时不给出相同的值?