C++ 中的 std::hash 模板类
本文将介绍 C++ 中来自 STL 的 std::hash
模板类。
使用 std::hash
为 std::string
对象生成哈希
std::hash
模板类在 STL <functional>
标头下提供。它创建一个哈希函数对象。std::hash
满足 DefaultConstructible
类型的要求,它只需要提供模板参数。
C++ 标准库中提供了这个模板类的多个默认特化,完整列表可以在这里看到。一旦使用给定的模板参数创建了散列函数对象,就可以使用它来生成特定的散列值,使用 operator()
接受单个参数并返回 size_t
值。
在下一个示例中,我们使用 string
特化并为任意字符串生成一些哈希值。
#include <iostream>#include <iomanip>#include <functional>using std::cout; using std::endl;
using std::setw; using std::string;
int main() {
string str1("arbitrary string");
std::vector<string> vec2 = {"true", "false", "false", "true", "false", "true"};
std::hash<string> str_hash;
cout << "hash(str1) - " << str_hash(str1) << endl;
cout << "hash(vec2 elements) - ";
for (const auto &item : vec2) {
cout << str_hash(item) << ", ";
}
cout << endl;
return EXIT_SUCCESS;
}
输出:
hash(str1) - 3484993726433737991
hash(vec2 elements) - 1325321672193711394, 3658472883277130625, 3658472883277130625, 1325321672193711394, 3658472883277130625, 1325321672193711394,
使用 std::hash
为 std::bitset
对象生成哈希
STL 中提供的 std::hash
的另一个专门化是用于 std::bitset
参数。请记住,std::bitset
是将固定数量的位表示为序列的类,它提供了多个成员函数以方便位操作。
通常,std::hash
特化使用的散列函数是依赖于实现的,不应将这些对象用作散列问题的通用解决方案。此外,这些散列函数只需要在程序的单次执行中为相同的输入产生相同的输出。
#include <iostream>#include <iomanip>#include <functional>#include <bitset>using std::cout; using std::endl;
using std::setw; using std::string;
int main() {
std::bitset<8> b1("00111001");
std::hash<std::bitset<8>> bitset_hash;
cout << "hash(bitset<8>) - " << bitset_hash(b1) << endl;
return EXIT_SUCCESS;
}
输出:
hash(bitset<8>) - 6623666755989985924
使用 std::hash
为 std::vector<bool>
对象生成哈希
我们还可以对布尔值的 vector
使用 std::hash
特化,如下面的代码片段所示。请注意,std::hash
也可以为用户定义的类进行专业化处理,一些额外的专业化处理可以通过 Boost 库来实现(详细内容见这里。
#include <iostream>#include <iomanip>#include <functional>using std::cout; using std::endl;
using std::setw; using std::string;
int main() {
std::vector<bool> vec1 = {true, false, false, true, false, true};
std::hash<std::vector<bool> > vec_str_hash;
cout << "hash(vector<bool>) - " << vec_str_hash(vec1) << endl;
return EXIT_SUCCESS;
}
输出:
hash(vector<bool>) - 12868445110721718657
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。