std::hash<std::basic_string>
来自 zh.cppreference.net
| 定义于头文件 <string>
|
||
template< class A >
struct hash<std::basic_string<char, std::char_traits<char>, A>>;
|
(1) | (C++11 起) |
template< class A >
struct hash<std::basic_string<char16_t, std::char_traits<char16_t>, A>>;
|
(2) | (C++11 起) |
template< class A >
struct hash<std::basic_string<char32_t, std::char_traits<char32_t>, A>>;
|
(3) | (C++11 起) |
template< class A >
struct hash<std::basic_string<wchar_t, std::char_traits<wchar_t>, A>>;
|
(4) | (C++11 起) |
template< class A >
struct hash<std::basic_string<char8_t, std::char_traits<char8_t>, A>>;
|
(5) | (C++20 起) |
针对各种字符串类的 std::hash 模板特化允许用户获取字符串的哈希值。
|
这些哈希值与对应 std::basic_string_view 类的哈希值相等:若 |
(C++17 起) |
示例
以下代码展示了哈希函数作用于字符串时可能的一种输出结果:
运行此代码
#include <functional> #include <iostream> #include <memory_resource> #include <string> #include <string_view> using namespace std::literals; int main() { auto sv = "Stand back! I've got jimmies!"sv; std::string s(sv); std::pmr::string pmrs(sv); // use default allocator std::cout << std::hash<std::string_view>{}(sv) << '\n'; std::cout << std::hash<std::string>{}(s) << '\n'; std::cout << std::hash<std::pmr::string>{}(pmrs) << '\n'; }
可能的输出:
3544599705012401047 3544599705012401047 3544599705012401047
缺陷报告
以下行为变更缺陷报告被追溯应用于先前发布的C++标准。
| DR | 适用范围 | 发布时的行为 | 正确行为 |
|---|---|---|---|
| LWG 3705 | C++11 | 未启用对使用自定义分配器的 std::basic_string 的哈希支持 | 已启用 |
参见
|
(C++11)
|
哈希函数对象
(类模板) |
|
(C++17)
(C++17)
(C++20)
(C++17)
(C++17)
|
字符串视图的哈希支持
(类模板特化) |