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.
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.
In C++03, boost::hash. In C++11, std::hash.
std::hash<std::string>()("foo");
boost::hash is not C++03, but boost. In environments that support tr1 (much more widely available than C++11), you can use std::tr1::hash<T>, defined in <tr1/functional>.boost::hash is not a part of C++03 the way, for example, std::string is. I also pointed out that std::tr1::hash is an alternative available in some environments where boost isn't. It was a well-intentioned suggestion to improve an otherwise good answer, at which Cat Plus Plus unfortunately took offense.tr1::hash is not part of C++03 either. Of course, you're right that it's useful to mention both the tr1 and boost solutions, because someone might be able to use one or the other but not both. but originally you presented it as if tr1 was somehow "more C++03" than boost is, which is nonsense. :)Boost provides a hash function:
#include <boost/functional/hash.hpp>
int hashCode()
{
boost::hash<std::string> string_hash;
return string_hash("Hash me");
}
std::hash instead. What is the advantage of boost?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;
}
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;
}
//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;
}