sufyan siddique
sufyan siddique

Reputation: 1481

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

Following java code returns hash code of a string.

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.

Upvotes: 23

Views: 78326

Answers (6)

Aero
Aero

Reputation: 77

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

Upvotes: 2

Javier Gonzalez
Javier Gonzalez

Reputation: 31

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

Upvotes: 1

user177800
user177800

Reputation:

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

Upvotes: 5

tune2fs
tune2fs

Reputation: 7705

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

Upvotes: 14

Megatron
Megatron

Reputation: 2949

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

Upvotes: 3

Cat Plus Plus
Cat Plus Plus

Reputation: 129954

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

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

Upvotes: 75

Related Questions