对于短字符串来说,这是一个很好的哈希函数吗?
Is this a good hashing function for short strings?
对于 10-50 个字符的字符串:
double hash(const std::string & str)
{
double result = 0;
int n=str.length();
for(int i=0;i<n;i++)
{
result += (str[i] - '@')*pow(256.0,i);
}
return result;
}
这可以用于生产代码吗?
- 通过 ILP 提高与 std::hash 一起使用时哈希的总吞吐量
- 正确性/唯一性
- 可扩展性
新版本评论:
double hash(const std::string & str)
{
double result = 0;
int n=str.length();
// maybe using multiple adders to do concurrently multiple chars
// since they are not dependent
for(int i=0;i<n;i++)
{
result += lookupCharDoubleType[str[i]]*lookupPow[i];
}
return result;
}
另一个评论的另一个版本:
double hash(const std::string & str)
{
double result = 0;
int n=str.length();
for(int i=0;i<n;i++)
{
result = result * 256.0 + lookupCharDoubleType[str[i]];
}
return result;
}
对于短字符串来说,这是一个很好的哈希函数吗?
不,这不是唯一性的好哈希值。您基本上是将字符串映射到double
上。对于长度为 50 个字符的字符串,您将获得一个256 ^^ 50
量级的值,即 2.58e120。这完全在双精度的范围内,即 1.7e308,但你必须明白,double
并不能准确表示数字——毕竟它只有 8 个字节长。
您的代码将字符串映射到double
,就好像字符是 256 进制数字一样,第一个字符是最不重要的数字:
字符串hello
映射如下:
'h' * 256^^0 + 'e'*256^^1 + 'l' * 256^^2 + 'l' * 256^^3 + 'o' * 256^^4
对于大于几个字节的字符串,最后字符将是结果中最重要的部分,所有其他字符将被完全删除,因为double
没有表示所有这些位的精度。
最终结果是你的哈希函数只会考虑最后几个字符。每当字符串中的任何字符更改时,一个好的哈希函数都应该更改,因此相似但不完全相同的字符串极不可能具有相同的哈希值。对于您的函数,只要最后几个字符相同,哈希值就可能相同。
相关文章:
- 在 C++11 中利用 int*_t、int_fast*_t 和 int_least*_t 之间的差异的一个很好的例子是
- 对于短字符串来说,这是一个很好的哈希函数吗?
- 是否有一个很好的方法可以在C 11中打印出像JSON一样的Trie结构(仅迭代解决方案)的扁平命名空间
- 为什么这会在Java中给我一个ClasscastException,而它在C 中效果很好
- 将libstdc 静态链接起来是一个很好的做法
- 有一个标准的容器可以很好地回收吗
- 用"gcc -c"通关很好地编译一个C++程序。为什么?
- 对于这个特定用例来说,一个很好的排序算法
- 一个很好的支持 c++ 联合的替代方案
- 有没有一个很好的通用方法来用ruby包装swig生成的类
- boost asio和c++11是一个很好的匹配
- 这是"mutable" C++的一个很好的用例吗?
- 一个很好的向量散列函数
- 当我为调试Lua编译程序时,运行得很好,但为什么我要为发布版编译它,我得到了一个c0000005错误
- 将类的std::vector作为同一类的属性是一个很好的设计选择
- 一个很好的例子说明了如何使函数primitve param const导致编译器优化
- 一个很好的算法来获得元素的闲置组合
- std::move(*this)是一个很好的模式吗?
- Qt:在c++类中有一个未声明为指针的小部件字段是很好的
- 如果我把这些都放到另一个函数里,是不是很好