c++ - 如何哈希一个三态二维数组?

标签 c++ hash

考虑以下代码。在 unordered_map 中使用 Key 中的数组的好的散列函数是什么?

#include <unordered_map>

using namespace std;

enum TriState {
    S0 = -1,
    S1 = 0,
    S2 = +1
};

struct K { // Key for the map
    TriState a[8][8];
    bool operator==(const K& k1) const {
        for (int i = 0; i < 64; i++)
            if (k1.a[0][i] != a[0][i])
                return false;
        return true;
    }
};

struct Hash {
    size_t operator()(const K& k) const {
        size_t s;
        // s = what is a good hash value?
        return s;
    }
};

unordered_map<K, int, Hash> m;

最佳答案

这个算法应该很快并且提供近乎均匀的散列:

size_t s = 0x3a7eb429; // Just some random seed value
for (int i = 0; i != 8; ++i)
{
    for (int j = 0; j != 8; ++j)
    {
        s = (s >> 1) | (s << (sizeof(size_t) * 8 - 1));
        s ^= k.a[i][j] * 0xee6b2807;
    }
}
s *= 0xee6b2807;
s ^= s >> 16;

在那之后,如果你想让散列更强大,再次使用 hash s 例如 MurmurHash3 .

关于c++ - 如何哈希一个三态二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8535060/

相关文章:

c++ - 'cin'和 'getline'问题的真正解决方案

c++ - 如何检查 CPLEX C++ 中是否已存在约束?

c++ - 逐行散列文件时错误的 md5 散列值

r - 为什么NaN和Inf-Inf的哈希值不同?

c++ - 来自 `boost::asio::streambuf`

c++ - 如何使用 CIN 从文件中读取值(64 位整数)

c++ - 如何解决LNK2001

jquery - Window.location.hash 需要语法帮助

git - 我如何在 Git 中 pull 单个提交?

ruby - 如何有效地从哈希的哈希中提取具有特定键名的所有值?