how to get hash code of a string in c++
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;
}
In C++03, boost::hash
. In C++11, std::hash
.
std::hash<std::string>()("foo");
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");
}