Namespaces
Variants

std:: hash<Key>:: operator()

From cppreference.net
Utilities library
std::hash
hash::operator()

Especializaciones de std::hash deben definir un operator() que:

  • Toma un único argumento key de tipo Key .
  • Retorna un valor de tipo std:: size_t que representa el valor hash de key .
  • Para dos parámetros k1 y k2 que son iguales, std:: hash < Key > ( ) ( k1 ) == std:: hash < Key > ( ) ( k2 ) .
  • Para dos parámetros diferentes k1 y k2 que no son iguales, la probabilidad de que std:: hash < Key > ( ) ( k1 ) == std:: hash < Key > ( ) ( k2 ) debería ser muy pequeña, aproximándose a 1.0 / std:: numeric_limits < size_t > :: max ( ) .

Contenidos

Parámetros

key - el objeto a ser hasheado

Valor de retorno

Un std:: size_t que representa el valor hash.

Excepciones

Las funciones hash no deben lanzar excepciones.

Ejemplo

El siguiente código muestra cómo especializar la plantilla std::hash para una clase personalizada. La función hash utiliza el algoritmo de hash Fowler–Noll–Vo .

#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';
}

Salida:

12615575401975788567