如何在c++中获得字符串的哈希码

how to get hash code of a string in c++

本文关键字:字符串 哈希码 c++      更新时间:2023-10-16

下面的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; 
}