Any built-in hash method in C ++?

I was looking for md5 for C ++, and I understand that md5 is not built-in (although there are many very good libraries to support the md5 function). Then I realized that I really do not need md5, any hashing method will do. So, I was wondering if C ++ has such functions? I mean hash functions built in?

While I was learning C ++, I saw that Java, PHP, and some other programming languages ​​support md5. For example, in PHP you just need to call: md5("your string"); .

Simple hash function. (If possible, provide a simple code on how to use it.)

+8
c ++ function hash
source share
3 answers

It's simple. With C ++ 11 you get

 hash<string> 

which you can use this way (untested, but gives you an idea):

 hash<string> h; const size_t value = h("mystring"); 

If you don't have C ++ 11, take a look at boost, perhaps boost::tr1::hash_map . They probably also provide a hash function for strings.

For very simple cases, you can start with something in this direction:

 size_t h = 0 for(int i=0; i<s.size(); ++i) h = h*31 + s[i]; return h; 

To accept this comment below. To prevent short lines from clustering, you can initialize h in different ways. Perhaps you can use length for this (but this is just my first idea, unproven):

 size_t h = numeric_limits::max<size_t>() / (s.length()+1); // +1: no div-by-0 ... 

It should not be worse than before, but still far from perfect.

+11
source share

It depends on which version of C ++ you have ... and which hash function you are looking for.

In C ++ 03, there is no hash container, and therefore there is no need for hashing. However, many compilers offered custom headers. Otherwise, Boost.Functional.Hash can help.

C ++ 0x has a family of unordered_ containers and thus the predicate std::hash , which already works for standard C ++ types (at least the built-in types and std::string ).

However, this is a simple hash, good enough for hash cards, not for security .

If you are looking for a cryptographic hash, then the problem is completely different (and md5 is unstable), and you will need a library for (for example) the SHA-2 hash.

If you're looking for speed, check out CityHash and MurmurHash . Both have limitations, but they are highly optimized.

+8
source share

How about using boost, boost.functional / hash

+4
source share

All Articles