Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL Hash Functions

Does the STL have any Hash functions available, that are exposed publicly?

I know that there are some non-standard implementations that use hash values (such as boost::hash_map), and MSVC8 implements a version of the hash_map/hash_set/etc.

But are there any Hash Functions that are defined in the C++98 STL?

If not, what are the best non-C++98 sources of a reliable hash function?

Order of preferred sources (from most acceptable to least): Boost, C++0x standard STL, TR1, other 3rd party.

like image 976
J T Avatar asked Apr 13 '11 17:04

J T


People also ask

What hash function is used in STL?

The unordered_map::hash_function() is a built in function in C++ STL which is used to get the hash function. This hash function is a unary function which takes a single argument only and returns a unique value of type size_t based on it.

What does std :: hash do?

std::hash<const char*> produces a hash of the value of the pointer (the memory address), it does not examine the contents of any character array.

How do you hash a string in C++?

using c++11, you can: #include <string> #include <unordered_map> std::size_t h1 = std::hash<std::string>{}("MyString"); std::size_t h2 = std::hash<double>{}(3.14159);

Is STD hash unique?

That means you can only have 256 unique hashes of arbitrary inputs. Since you can definitely create more than 256 different strings, there is no way the hash would be unique for all possible strings.


2 Answers

to summarize:

  • The STL has hash functions
  • The C++98 standard library does not
  • The C++ TR1 has hash functions (6.3.3[tr.unord.hash])
  • boost has hash functions
  • The C++11 standard library has hash functions (20.8.12[unord.hash])

And all of them are designed for hashed associative containers, not for cryptography.

like image 151
Cubbi Avatar answered Sep 19 '22 12:09

Cubbi


I guess you're looking for hash functions for hash tables, not for cryptography, correct?

In that case, what about boost::hash?

The documentation says it's compatible with the TR1 hash, which should become part of the upcoming C++0x standard. That means it's probably already found in quite a few compilers.

For cryptographic hashes, there seems to be a SHA-1 implementation in Boost, but the way to go if you need them heavyweight is to use a dedicated library, such as Crypto++.

like image 36
Boaz Yaniv Avatar answered Sep 18 '22 12:09

Boaz Yaniv