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

来自cppreference.com
< cpp‎ | utility‎ | hash

 
 
实用工具库
类型的支持 (basic types, RTTI, type traits)
动态内存管理
错误处理
程序实用工具
可变参数函数
日期和时间
函数对象
initializer_list(C++11)
bitset
hash(C++11)
关系运算符
原文:
Relational operators
这段文字是通过 Google Translate 自动翻译生成的。
您可以帮助我们检查、纠正翻译中的错误。详情请点击这里
rel_ops::operator!=
rel_ops::operator>
rel_ops::operator<=
rel_ops::operator>=
双和元组
原文:
Pairs and tuples
这段文字是通过 Google Translate 自动翻译生成的。
您可以帮助我们检查、纠正翻译中的错误。详情请点击这里
pair
tuple(C++11)
piecewise_construct_t(C++11)
piecewise_construct(C++11)
掉期,远期和移动
原文:
Swap, forward and move
这段文字是通过 Google Translate 自动翻译生成的。
您可以帮助我们检查、纠正翻译中的错误。详情请点击这里
swap
forward(C++11)
move(C++11)
move_if_noexcept(C++11)
declval(C++11)
 
std::hash
hash::hash
hash::operator()
 

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().

目录

[编辑] 参数

key - the object to be hashed

[编辑] 返回值

a size_t representing the hash value

[编辑] 例外

Hash functions should not throw exceptions.

[编辑] 为例

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;
  unsigned int 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';
}

输出:

177237019