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

Da cppreference.com.
< cpp‎ | utility‎ | hash

 
 
Utilità libreria
Tipo di supporto (basic types, RTTI, type traits)
Gestione della memoria dinamica
La gestione degli errori
Programma di utilità
Funzioni variadic
Data e ora
Funzione oggetti
initializer_list(C++11)
bitset
hash(C++11)
Gli operatori relazionali
Original:
Relational operators
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
rel_ops::operator!=
rel_ops::operator>
rel_ops::operator<=
rel_ops::operator>=
Coppie e tuple
Original:
Pairs and tuples
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
pair
tuple(C++11)
piecewise_construct_t(C++11)
piecewise_construct(C++11)
Swap, in avanti e spostare
Original:
Swap, forward and move
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
swap
forward(C++11)
move(C++11)
move_if_noexcept(C++11)
declval(C++11)
 
 

Specializations of std::hash should define an operator() that:

  • Takes a single argument key of type Key.
  • Returns a value of type size_t that represents the hash value of key.
  • For two parameters k1 and k2 that are equal, std::hash<Key>()(k1)==std::hash<Key>()(k2).
  • For two different parameters k1 and k2 that are not equal, the probability that std::hash<Key>()(k1)==std::hash<Key>()(k2) should be very small, approaching 1.0/std::numeric_limits<size_t>::max().

Indice

[modifica]Parametri

key - the object to be hashed

[modifica]Valore di ritorno

a size_t representing the hash value

[modifica]Eccezioni

Hash functions should not throw exceptions.

[modifica]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;unsignedint 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
close