std::hash<Key>::operator()
Da cppreference.com.
|
|
Questa pagina è stata tradotta in modo automatico dalla versione in ineglese della wiki usando Google Translate.
La traduzione potrebbe contenere errori e termini strani. Muovi il puntatore sopra al testo per vedere la versione originale. Puoi aiutarci a correggere gli gli errori. Per ulteriori istruzioni clicca qui. |
<metanoindex/>
Specializations of std::hash should define an operator() that:
- Takes a single argument
keyof typeKey. - Returns a value of type
size_tthat represents the hash value ofkey. - For two parameters
k1andk2that are equal,std::hash<Key>()(k1) == std::hash<Key>()(k2). - For two different parameters
k1andk2that are not equal, the probability thatstd::hash<Key>()(k1) == std::hash<Key>()(k2)should be very small, approaching1.0/std::numeric_limits<size_t>::max().
Parametri
| key | - | the object to be hashed |
Valore di ritorno
a size_t representing the hash value
Eccezioni
Hash functions should not throw exceptions.
Esempio
The following code shows how to specialize the std::hash template for a custom class.
#include <functional>
#include <iostream>
#include <string>
struct Employee {
std::string name;
unsigned int ID;
};
namespace std {
template <>
class hash<Employee> {
public:
size_t operator()(const Employee &employee) const
{
// computes the hash of an employee using a variant
// of the Fowler-Noll-Vo hash function
size_t result = 2166136261;
for (size_t i = 0, ie = employee.name.size(); i != ie; ++i) {
result = (result * 16777619) ^ employee.name[i];
}
return result ^ (employee.ID << 1);
}
};
}
int main()
{
Employee employee;
employee.name = "Zaphod Beeblebrox";
employee.ID = 42;
std::hash<Employee> hash_fn;
std::cout << hash_fn(employee) << '\n';
}
Output:
177237019