C++计算array<int,3>的hash,要求是不直接使用stl的hash
Jump to turn (10)
- User
C++计算array<int,3>的hash,要求是不直接使用stl的hash
- Assistant
可以使用经典的哈希函数:乘法哈希。其基本原理是将 key 映射到一个足够大的整数范围内。具体步骤如下:
- 选择一个大质数 p,通常为质数或 2 的幂
- 选择一个常数 a,0 < a < p
- 对 key 中的每个元素,计算 h = (h * a + key[i]) % p,其中 h 初值为 0
- 返回 h
实现如下:
codeint hash(const std::array<int, 3>& arr) { const int p = 73856093; // 质数,足够大 const int a = 161; // 小于 p,与 p 互质 int h = 0; for (int i=0; i<3; ++i) { h = (h * a + arr[i]) % p; } return h; }上述代码中,p 取一个足够大的质数,a 取一个小于 p 的数,广泛认可的 a 值是 31 或者 37,但也可以尝试其他值。最后,返回计算得到的 h 值即可。
- User
C++常见的hash计算方式,多罗列几种写法
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.