Namespaces
Variants

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

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

std::hash 의 특수화는 다음을 충족하는 operator() 를 정의해야 합니다:

  • 단일 인수 key Key 타입으로 받습니다.
  • std:: size_t 타입의 값을 반환하며, 이는 key 의 해시 값을 나타냅니다.
  • 동일한 두 매개변수 k1 k2 에 대해 std:: hash < Key > ( ) ( k1 ) == std:: hash < Key > ( ) ( k2 ) 가 성립합니다.
  • 서로 다른 두 매개변수 k1 k2 가 다른 경우, std:: hash < Key > ( ) ( k1 ) == std:: hash < Key > ( ) ( k2 ) 일 확률은 매우 작아야 하며, 1.0 / std:: numeric_limits < size_t > :: max ( ) 에 근접해야 합니다.

목차

매개변수

key - 해시될 객체

반환값

해시 값을 나타내는 std:: size_t 입니다.

예외

해시 함수는 예외를 던지지 않아야 합니다.

예제

다음 코드는 사용자 정의 클래스에 대해 std::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';
}

출력:

12615575401975788567