std::hash<std::basic_string>
來自 cppreference.com
< cpp | string | basic_string
定義於標頭檔案 <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++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 3705 | C++11 | 對帶有自定義分配器的 std::basic_string 的雜湊支援未啟用 | 已啟用 |
[編輯] 參閱
(C++11) |
雜湊函式物件 (類模板) |
字串檢視的雜湊支援 (類模板特化) |