如何在c++中获得字符串的哈希码
how to get hash code of a string in c++
下面的java代码返回字符串的哈希码。
String uri = "Some URI"
public int hashCode() {
return uri.hashCode();
}
我想把这段代码翻译成c++。在c++中是否有任何可用的函数或简单的方法来翻译它?
在c++ 03中,boost::hash
。在c++ 11中,std::hash
.
std::hash<std::string>()("foo");
Boost提供哈希函数:
提高哈希
#include <boost/functional/hash.hpp>
int hashCode()
{
boost::hash<std::string> string_hash;
return string_hash("Hash me");
}
以下是Java中默认String.hashCode()
的源代码,这是在c++中实现的一个微不足道的练习。
public int hashCode()
{
int h = hash;
if (h == 0 && count > 0)
{
int off = offset;
char val[] = value;
int len = count;
for (int i = 0; i < len; i++)
{
h = 31*h + val[off++];
}
hash = h;
}
return h;
}
我个人喜欢使用boost的哈希函数
http://www.boost.org/doc/libs/1_47_0/doc/html/hash.html创建字符串散列非常简单,
boost::hash<std::string> string_hash;
std::size_t h = string_hash("Hash me");
新版本的c++有一个等价的std::hash
我遇到了和你一样的问题,希望这段代码能帮助你:
int HashCode (const std::string &str) {
int h = 0;
for (size_t i = 0; i < str.size(); ++i)
h = h * 31 + static_cast<int>(str[i]);
return h;
}
//对于c++ Qt,您可以使用此代码,结果与Java hashcode()
相同int hashCode(QString text){
int hash = 0, strlen = text.length(), i;
QChar character;
if (strlen == 0)
return hash;
for (i = 0; i < strlen; i++) {
character = text.at(i);
hash = (31 * hash) + (character.toAscii());
}
return hash;
}
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 如何为字符串生成唯一但一致的 N 位哈希(小于 64 位)?
- 对于短字符串来说,这是一个很好的哈希函数吗?
- 我的求解(字符串 a、字符串 b)的输出与随机哈希中的预期输出不匹配
- 我可以比朴素哈希表更快地将随机字符串映射到两个类吗?
- 自定义哈希表实现-将字符串映射到整数时出现内存错误
- 在 cpp 自己的版本中对字符串进行哈希处理
- 哈希字符串更改大小写
- C 字符串哈希散列字符串或内存地址吗?
- 在C++中返回简单哈希码的函数
- 有关忽略字符顺序的字符串哈希函数的建议
- 适用于短文件名的最佳字符串哈希函数
- 此示例的最佳字符串哈希函数
- 多项式哈希码导致负数
- 哈希图实现:---哈希码
- 使用异或和位移位的字符串哈希算法
- 如何在c++中获得字符串的哈希码
- 在哈希表中创建字符串哈希值的时间复杂度
- 在C++中真正编译时字符串哈希
- 在我的情况下,我如何重载相等的方法以使不同的对象在unordered_multimap具有相同的哈希码值