我有一个用 C 定义的结构体,如下所示
typedef struct {
unsigned int size;
unsigned int pool_size;
route _routes[SIZE_OF_FLEET];
request _request_pool[SIZE_OF_PROBLEM];
/* stores which request is contained in which route */
unsigned int _request_map[SIZE_OF_PROBLEM];
} solution;
我正在尝试为这个结构定义一个散列函数,如下所示
unsigned long long solution_hash(solution const *_sol)
{
unsigned long long hash = 0;
unsigned short c;
unsigned short *reinterpret_sol;
reinterpret_sol = (unsigned short*)&_sol;
size_t size_ = sizeof(solution);
size_t elem_size_ = sizeof(unsigned short);
int len = (int)size_/elem_size_;
for (int i = 0; i < len; i++) {
c = reinterpret_sol[i];
hash += c;
}
return hash;
}
问题是每次调用 solution_hash 函数时,相同解决方案的哈希值都会发生变化。对于同一解决方案,连续调用将值增加 32。
这段代码有什么问题?有没有更好的方法来为结构体实现哈希函数?
最佳答案
Casting 隐藏了 @Eugene Sh. 指出的问题
// reinterpret_sol = (unsigned short*)&_sol;
reinterpret_sol = (unsigned short*) _sol;
关于在C中计算结构的哈希值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38485502/