【发布时间】:2016-11-23 22:34:28
【问题描述】:
我在 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。
这段代码有什么问题?有没有更好的方法来实现结构的哈希函数?
【问题讨论】:
-
reinterpret_sol = (unsigned short*)&_sol;- 你确定&吗?在任何情况下看起来都像打破 strict aliasing 规则.. -
哦,非常感谢。我试了好几个小时代码出了什么问题,你不到一分钟就弄明白了:)
-
即使你修复了
&和严格的别名冲突,这看起来你可以很容易地最终散列结构内的填充。此外,简单的加法是混合c值的一种非常糟糕的方法。 -
@EugeneSh.:C11 final draft, section 6.2.6.1, part 6:“当一个值存储在结构或联合类型的对象中时,包括在成员对象中,对应于任何填充字节的对象表示的字节采用未指定的值。”填充字节不一致。
-
供参考(帮助决策):stackoverflow.com/questions/996843/…