Following java code returns hash code of a string.
String uri = \"Some URI\"
public int hashCode() {
return uri.hashCode();
}
I want t
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;
}
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");
}
//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;
}
In C++03, boost::hash
. In C++11, std::hash
.
std::hash<std::string>()("foo");
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
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;
}