class template
<functional>
std::hash
template <class T> struct hash;
Default hash function object class
Unary function object class that defines the default hash function used by the standard library.
The functional call returns a hash value of its argument: A hash value is a value that depends solely on its argument, returning always the same value for the same argument (for a given execution of a program). The value returned shall have a small likelihood of being the same as the one returned for a different argument (with chances of collision approaching 1/numeric_limits<size_t>::max
).
Other function object types can be used as Hash for unordered containers provided they behave as defined above and they are at least copy-constructible, destructible function objects.
The default hash is a template class that is not defined for the general case. But all library implementations provide at least the following type-specific specializations:
Apart from being callable with an argument of the appropriate types, all objects of hash instantiations are default-constructible, copy-constructible, copy-assignable, destructible and swappable.
Users can provide custom specializations for this template with these same properties.
Member types
member type | definition | notes |
result_type | size_t | The type of the hash values produced. |
argument_type | T | The type of the values taken as argument. |
Member functions
- operator()
- Returns a hash value for its argument, as a value of type size_t.
size_t is an unsigned integral type.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
// hash example
#include <iostream>
#include <functional>
#include <string>
int main ()
{
char nts1[] = "Test";
char nts2[] = "Test";
std::string str1 (nts1);
std::string str2 (nts2);
std::hash<char*> ptr_hash;
std::hash<std::string> str_hash;
std::cout << "same hashes:\n" << std::boolalpha;
std::cout << "nts1 and nts2: " << (ptr_hash(nts1)==ptr_hash(nts2)) << '\n';
std::cout << "str1 and str2: " << (str_hash(str1)==str_hash(str2)) << '\n';
return 0;
}
| |
Output:
same hashes:
nts1 and nts2: false
str1 and str2: true
|
Exception safety
No-throw guarantee: no members throw exceptions (this applies to the specializations provided in the library implementation). Custom specializations may provide different guarantees.