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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8094790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:59:04  来源:igfitidea点击:

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

c++stringhashhashcode

提问by sufyan siddique

Following java code returns hash code of a string.

以下 java 代码返回字符串的哈希码。

String uri = "Some URI"
public int hashCode() {
    return uri.hashCode();
}

I want to translate this code to c++. Is there any function availabe in c++ or an easy way to translate this.

我想将此代码转换为 C++。在 C++ 中是否有任何可用的函数或一种简单的方法来翻译它。

采纳答案by tune2fs

Boost provides a hash function:

Boost 提供了一个哈希函数:

boost hash

提升哈希

#include <boost/functional/hash.hpp>

int hashCode()
{
    boost::hash<std::string> string_hash;

    return string_hash("Hash me");
}

回答by Cat Plus Plus

In C++03, boost::hash. In C++11, std::hash.

在 C++03 中,boost::hash. 在 C++11 中,std::hash.

std::hash<std::string>()("foo");

回答by tune2fs

The following is the source for the default String.hashCode()in Java, this is a trival exercise to implement in C++.

以下是String.hashCode()Java 中默认值的源代码,这是在 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;
   }

回答by Megatron

Personally, I like to use boost's hash functions

就个人而言,我喜欢使用 boost 的哈希函数

http://www.boost.org/doc/libs/1_47_0/doc/html/hash.html

http://www.boost.org/doc/libs/1_47_0/doc/html/hash.html

making a string hash is pretty simple,

制作字符串哈希非常简单,

boost::hash<std::string> string_hash;

std::size_t h = string_hash("Hash me");

newer versions of C++ have an equivalent with std::hash

较新版本的 C++ 与 std::hash 等效

回答by Javier Gonzalez

//For C++ Qt you can use this code, the result is the sames as for Java hashcode()

//对于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; 
}

回答by Aero

I encoutered the same question as you have, hope this code will help you :

我遇到了和你一样的问题,希望这段代码能帮助你:

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;
}