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

前端 未结 6 1642
庸人自扰
庸人自扰 2020-11-30 06:07

Following java code returns hash code of a string.

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

I want t

相关标签:
6条回答
  • 2020-11-30 06:26

    The following is the source for the default String.hashCode() in Java, this is a trival exercise to implement in 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;
       }
    
    0 讨论(0)
  • 2020-11-30 06:30

    Boost provides a hash function:

    boost hash

    #include <boost/functional/hash.hpp>
    
    int hashCode()
    {
        boost::hash<std::string> string_hash;
    
        return string_hash("Hash me");
    }
    
    0 讨论(0)
  • 2020-11-30 06:30

    //For C++ Qt you can use this code, the result is the sames as for 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; 
    }
    
    0 讨论(0)
  • 2020-11-30 06:37

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

    std::hash<std::string>()("foo");
    
    0 讨论(0)
  • 2020-11-30 06:38

    Personally, I like to use boost's hash functions

    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

    0 讨论(0)
  • 2020-11-30 06:38

    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;
    }
    
    0 讨论(0)
提交回复
热议问题