Home C&C++函数库 c++ 语法 程序源码 Linux C库

std::

hash

类模板  <functional>

template <class T> struct hash;

默认哈希函数对象类
一元函数对象类,它定义标准库使用的默认哈希函数。

函数调用返回参数的哈希值:哈希值是完全依赖于其参数的值,总是为相同的参数返回相同的值(对于给定的程序执行)。
返回的值有很小的可能与另一个参数返回的值相同(碰撞的几率接近 1/numeric_limits<size_t>::max)。

其他函数对象类型可以用作无序容器的哈希,前提是它们的行为与上面定义的一样,并且它们至少是可复制构造、可销毁的函数对象。

默认哈希是未为一般情况定义的模板类。但所有库实现至少提供以下特定于类型的特化:
头文件 类型
<functional> bool
char
signed char
unsigned char
char16_t
char32_t
wchar_t
short
unsigned short
int
unsigned int
long
unsigned long
long long
unsigned long long
float
double
long double
T* (for any type T)
<string> string
wstring
u16string
u32string
<memory> unique_ptr
shared_ptr
<vector> vector<bool>
<bitset> bitset
<system_error> error_code
<typeindex> type_index
<thread> thread::id
除了可以通过适当类型的参数调用外,所有哈希例化的对象都是默认可构造、可复制可构造、可复制赋值的、可销毁的和可交换的。

用户可以为这个模板提供具有这些相同属性的自定义特化。

☲  成员类型


成员类型 定义 注释
result_type size_t 生成的哈希值的类型。
argument_type T 作为参数的值的类型。

☲  成员函数



operator()
返回参数的size_t类型的哈希值。
Size_t是一个无符号整型。

☣  示例



// hash example
#include <iostream>
#include <functional>
#include <string>

int main ()
{
  char nts1[] = "Test";
  char nts2[] = "Test";
  std::string str1 (nts1);
  std::string str2 (nts2);

  std::hash<char*> ptr_hash;
  std::hash<std::string> str_hash;

  std::cout << "same hashes:\n" << std::boolalpha;
  std::cout << "nts1 and nts2: " << (ptr_hash(nts1)==ptr_hash(nts2)) << '\n';
  std::cout << "str1 and str2: " << (str_hash(str1)==str_hash(str2)) << '\n';

  return 0;
}

输出:
same hashes:
nts1 and nts2: false
str1 and str2: true

☂ 异常安全性



no -throw保证:没有成员抛出异常(这适用于库实现中提供的特化)。自定义特化可能提供不同的保证。
联系我们 免责声明 关于CandCplus 网站地图