Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

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

      From cppreference.com
      <cpp‎ |utility‎ |hash
       
       
      Utilities library
       
       

      Specializations ofstd::hash should define anoperator() that:

      • Takes a single argumentkey of typeKey.
      • Returns a value of typestd::size_t that represents the hash value ofkey.
      • For two parametersk1 andk2 that are equal,std::hash<Key>()(k1)==std::hash<Key>()(k2).
      • For two different parametersk1 andk2 that 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().

      Contents

      [edit]Parameters

      key - the object to be hashed

      [edit]Return value

      Astd::size_t representing the hash value.

      [edit]Exceptions

      Hash functions should not throw exceptions.

      [edit]Example

      The following code shows how to specialize thestd::hash template for a custom class. The hash function usesFowler–Noll–Vo hash algorithm.

      Run this 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 functionconstexprstd::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';}

      Output:

      12615575401975788567
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/utility/hash/operator()&oldid=172710"

      [8]ページ先頭

      ©2009-2025 Movatter.jp