如何为 std::vector<std::vector 编写哈希函数<bool>>

How to write a hash function for a std::vector<std::vector<bool>>

本文关键字:gt vector lt std 函数 bool 哈希      更新时间:2023-10-16

我有一个结构体,它有一个变量,一个代表网格的std::vector<std::vector<bool>>。如果网格相等,或者网格的任何旋转相等,这些结构中的一个就等于另一个。我试图使用unordered_set来存储其中的许多,然而,经过一些研究,我发现我需要某种哈希函数。我以前从来没有使用过哈希函数,我发现的关于它的东西让我很困惑。所以,我的问题是,我如何/什么是为这种数据类型编写哈希函数的最佳方法,或者更好的方法是使用一组无序的网格并在添加它们时测试旋转?

一些代码:

int nx, ny;
typedef std::vector<std::vector<bool>> grid;
struct rotateableGrid {
public:
    grid data;
    rotateableGrid(grid data) : data(data) {}
    rotateableGrid(rotateableGrid &rg) : data(rg.data) {}
    bool operator==(const rotateableGrid & rhs) {
        for (int c = 0; c < 4; c++) {
            if (rotate(c) == rhs.data) return true;
        }
        return false;
    }
private:
    grid rotate(int amt) {
        if (amt % 4 == 0) return data;
        grid ret(ny, std::vector<bool>(nx));
        for (int x = 0; x < nx; x++) {
            for (int y = 0; y < ny; y++) {
                switch (amt % 4) {
                case 1:
                    if (x < ny && nx - 1 - y >= 0) ret[x][nx - 1 - y] = data[y][x];
                    break;
                case 2:
                    if (nx - 1 - x >= 0 && ny - 1 - y >= 0) ret[ny - 1 - y][nx - 1 - x] = data[y][x];
                    break;
                case 3:
                    if (ny - 1 - x >= 0 && y < nx) ret[x][nx - 1 - y] = data[y][x];
                    break;
                default:
                    break;
                }
            }
        }
        return ret;
    }
};

提前感谢!

注意:我用c++在VS 2013

你可以做的是将矩阵中所有向量的哈希值组合起来。std::hashstd::vector<bool>过载。如果你尝试这样做

size_t hash_vector(const std::vector< std::vector<bool> >& in, size_t seed)
{
    size_t size = in.size();
    std::hash< std::vector<bool> > hasher;
    for (size_t i = 0; i < size; i++)
    {
        //Combine the hash of the current vector with the hashes of the previous ones
        seed ^= hasher(in[i]) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
    }
    return seed;
}

为了获得旋转不变性,你可以将所有网格旋转的哈希值组合在一起。正如@zch的评论所建议的那样,你会这样做

size_t hash_grid(rotateableGrid& in, size_t seed = 92821)
             //  ^^^^^ Should be const, but rotate isn't marked const
{
    return hash_vector(in.data) ^ hash_vector(in.rotate(1).data) ^ hash_vector(in.rotate(2).data) ^ hash_vector(in.rotate(3).data);
}

但是,因为rotateableGrid的旋转成员被标记为private,所以必须将hash_grid声明为rotateableGrid的友元。要做到这一点,你必须将它添加到rotateableGrid

的定义中
friend size_t hash_grid(rotateableGrid&, size_t);