Namespaces
Variants

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

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

Spezialisierungen von std::hash sollten einen operator() definieren, der:

  • Nimmt ein einzelnes Argument key vom Typ Key entgegen.
  • Gibt einen Wert vom Typ std:: size_t zurück, der den Hashwert von key repräsentiert.
  • Für zwei gleiche Parameter k1 und k2 gilt: std:: hash < Key > ( ) ( k1 ) == std:: hash < Key > ( ) ( k2 ) .
  • Für zwei unterschiedliche Parameter k1 und k2 sollte die Wahrscheinlichkeit, dass std:: hash < Key > ( ) ( k1 ) == std:: hash < Key > ( ) ( k2 ) , sehr gering sein und sich 1.0 / std:: numeric_limits < size_t > :: max ( ) annähern.

Inhaltsverzeichnis

Parameter

key - das zu hashende Objekt

Rückgabewert

Ein std:: size_t der den Hash-Wert repräsentiert.

Ausnahmen

Hash-Funktionen sollten keine Ausnahmen werfen.

Beispiel

Der folgende Code zeigt, wie die std::hash -Vorlage für eine benutzerdefinierte Klasse spezialisiert wird. Die Hash-Funktion verwendet den Fowler–Noll–Vo -Hash-Algorithmus.

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

Ausgabe:

12615575401975788567