I was looking for md5 for C++, and I realize md5 is not built in (even though there are a lot of very good libraries to support the md5 function). Then, I realized I don't actually need md5, any hashing method will do. Thus, I was wondering if C++ has such functions? I mean, built-in hashing functions?
While I was researching for C++, I saw Java, PHP, and some other programming languages support md5. For example, in PHP, you just need to call: md5("your string");
.
A simple hash function will do. (If possible, please include some simple code on how to use it.)
This is simple. With C++11 you get a
hash<string>
functor which you can use like this (untested, but gives you the idea):
hash<string> h;
const size_t value = h("mystring");
If you don't have C++11, take a look at boost, maybe boost::tr1::hash_map
. They probably provide a string-hashing function, too.
For very simple cases you can start with something along these lines:
size_t h = 0
for(int i=0; i<s.size(); ++i)
h = h*31 + s[i];
return h;
To take up the comment below. To prevent short strings from clustering you may want to initialize h
differently. Maybe you can use the length for that (but that is just my first idea, unproven):
size_t h = numeric_limits::max<size_t>() / (s.length()+1); // +1: no div-by-0
...
This should not be worse then before, but still far from perfect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With