Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any built in hash method in C++?

Tags:

c++

function

hash

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.)

like image 855
generator Avatar asked Jun 01 '11 11:06

generator


1 Answers

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.

like image 92
towi Avatar answered Oct 15 '22 12:10

towi