Alex Rivera | Logout

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

Asked 2011-11-11T13:42:25.007
23

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.

Edit
Report

2 Answers

75

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

std::hash<std::string>()("foo");
answered 2011-11-11T13:45:57.317
5

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;
   }
answered 2011-11-11T13:50:45.070

Your Answer