std:: hash<Key>:: operator()
From cppreference.net
C++
Utilities library
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
std::hash
|
hash::operator()
|
Les spécialisations de
std::hash
doivent définir un
operator()
qui :
-
Prend un seul argument
key
de type
Key. - Retourne une valeur de type std:: size_t qui représente la valeur de hachage de key .
-
Pour deux paramètres
k1etk2qui sont égaux, std:: hash < Key > ( ) ( k1 ) == std:: hash < Key > ( ) ( k2 ) . -
Pour deux paramètres différents
k1etk2qui ne sont pas égaux, la probabilité que std:: hash < Key > ( ) ( k1 ) == std:: hash < Key > ( ) ( k2 ) devrait être très faible, approchant 1.0 / std:: numeric_limits < size_t > :: max ( ) .
Table des matières |
Paramètres
| key | - | l'objet à hacher |
Valeur de retour
Un std:: size_t représentant la valeur de hachage.
Exceptions
Les fonctions de hachage ne doivent pas lever d'exceptions.
Exemple
Le code suivant montre comment spécialiser le modèle std::hash pour une classe personnalisée. La fonction de hachage utilise l'algorithme de hachage Fowler–Noll–Vo .
Exécuter ce code
#include <cstdint> #include <functional> #include <iostream> #include <string> struct Employee { std::string name; std::uint64_t ID; }; namespace std { template <> class hash<Employee> { public: std::uint64_t operator()(const Employee& employee) const { // computes the hash of an employee using a variant // of the Fowler-Noll-Vo hash function constexpr std::uint64_t prime{0x100000001B3}; std::uint64_t result{0xcbf29ce484222325}; for (std::uint64_t i{}, ie = employee.name.size(); i != ie; ++i) result = (result * prime) ^ 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'; }
Sortie :
12615575401975788567