如何为 std::vector<std::vector 编写哈希函数<bool>>
How to write a hash function for a std::vector<std::vector<bool>>
我有一个结构体,它有一个变量,一个代表网格的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::hash
对std::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);
相关文章:
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 在c++中用vector填充一个简单的动态数组
- vector.resize()中的分配错误
- 使用std::vector的OpenCL矩阵乘法
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 在某些循环内使用vector.push_back时出现分段错误
- 当vector是tje全局变量时,c++中vector的内存管理
- std::vector的包装器,使数组的结构看起来像结构的数组
- 为什么(-1)%vector::size()总是返回0
- 在C++中将类(带有Vector成员)保存为二进制文件
- 编译器如何区分std::vector的构造函数
- 将 int 数组转换为 std::vector<int*>
- 使用 pqxx 将 std::vector 存储在 postgresql 中,并从数据库中检索它
- EASTL矢量<向量<int>>连续的
- 在std::vector上存储带有模板的类实例
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ
- std::vector<;uint8_t>;当C++11/14启用时,手动复制而不是调用memcpy
- 使用 std::vector<boost::shared_ptr<Base_Class>> 或 boost::p tr_vector 的性能注意事项是什么<Base>
- 将矩阵"shared_ptr<vector<vector>sp"的行"(*sp)[i]"<T>传递给接受"shared_ptr<vector<T>>
- 如何获取std::vector<DMatch>