std::hash<std::string_view>,std::hash<std::wstring_view>,std::hash<std::u8string_view>,std::hash<std::u16string_view>,std::hash<std::u32string_view>
来自 cppreference.com
< cpp | string | basic string view
在头文件 <string_view> 中定义 |
||
template<> struct hash<std::string_view>; |
(自 C++17 起) | |
template<> struct hash<std::wstring_view>; |
(自 C++17 起) | |
template<> struct hash<std::u8string_view>; |
(自 C++20 起) | |
template<> struct hash<std::u16string_view>; |
(自 C++17 起) | |
template<> struct hash<std::u32string_view>; |
(自 C++17 起) | |
针对各种视图类进行视图散列的 std::hash 模板特化。
这些散列等于相应 std::basic_string 类的散列:如果 S 是标准 basic_string 类型之一,SV 是相应的字符串视图类型,并且 s 是类型 S 的对象,那么 std::hash<S>()(s) == std::hash<SV>()(SV(s)).
[编辑] 示例
运行此代码
#include <iostream> #include <string_view> #include <unordered_set> using namespace std::literals; int main() { std::cout << "\"A\" #: " << std::hash<std::string_view>{}("A"sv) << '\n'; std::cout << "L\"B\" #: " << std::hash<std::wstring_view>{}(L"B"sv) << '\n'; std::cout << "u8\"C\" #: " << std::hash<std::u8string_view>{}(u8"C"sv) << '\n'; std::cout << "u\"D\" #: " << std::hash<std::u16string_view>{}(u"D"sv) << '\n'; std::cout << "U\"E\" #: " << std::hash<std::u32string_view>{}(U"E"sv) << '\n'; // std::hash for string_view family makes it possible to keep these view-types // in unordered_* associative containers, such as unordered_set. But ensure // the lifespan of referenced strings is no less than lifespan of the container, // i.e. no dangling references occurred. std::unordered_set stars{"Rigel"sv, "Capella"sv, "Vega"sv, "Arcturus"sv}; for (std::string_view const& s : stars) std::cout << s << ' '; std::cout << '\n'; }
可能的输出
"A" #: 6919333181322027406 L"B" #: 11959850520494268278 u8"C" #: 12432341034569643010 u"D" #: 312659256970442235 U"E" #: 18073225910249204957 Arcturus Vega Capella Rigel
[编辑] 另请参见
(C++11) |
散列函数对象 (类模板) |
(C++11) |
对字符串的支持散列 (类模板特化) |