std::collate<CharT>::hash, std::collate<CharT>::do_hash
来自 cppreference.cn
定义于头文件 <locale> |
||
public: long hash( const CharT* beg, const CharT* end ) const; |
(1) | |
protected: virtual long do_hash( const CharT* beg, const CharT* end ) const; |
(2) | |
1) 公有成员函数,调用最派生类的受保护虚成员函数
do_hash
。2) 将字符序列
[
beg,
end)
转换为一个整数值,该值等于在此区域设置中整理等效的所有字符串的哈希值(compare() 返回 0)。对于两个整理不等效的字符串,它们的哈希值相等的概率应该非常小,接近 1.0 / std::numeric_limits<unsigned long>::max()。目录 |
[编辑] 参数
beg | - | 指向要哈希的序列中第一个字符的指针 |
end | - | 指向要哈希的序列的末尾后一个位置的指针 |
[编辑] 返回值
尊重排序规则的哈希值。
[编辑] 注意
系统提供的区域设置通常不会将两个字符串整理为等效(如果 basic_string::operator== 返回 false,则 compare() 不会返回 0),但是用户安装的 std::collate facet 可能会提供不同的排序规则,例如,如果字符串具有相同的 Unicode 规范化形式,则可能会将它们视为等效。
[编辑] 示例
演示了区域设置感知的无序容器。
运行此代码
#include <iostream> #include <locale> #include <string> #include <unordered_set> struct CollateHash { template<typename CharT> long operator()(const std::basic_string<CharT>& s) const { return std::use_facet<std::collate<CharT>>(std::locale()).hash( &s[0], &s[0] + s.size() ); } }; struct CollateEq { template<typename CharT> bool operator()(const std::basic_string<CharT>& s1, const std::basic_string<CharT>& s2) const { return std::use_facet<std::collate<CharT>>(std::locale()).compare( &s1[0], &s1[0] + s1.size(), &s2[0], &s2[0] + s2.size() ) == 0; } }; int main() { std::locale::global(std::locale("en_US.utf8")); std::wcout.imbue(std::locale()); std::unordered_set<std::wstring, CollateHash, CollateEq> s2 = {L"Foo", L"Bar"}; for (auto& str : s2) std::wcout << str << ' '; std::cout << '\n'; }
可能的输出
Bar Foo
[编辑] 参见
(C++11) |
字符串的哈希支持 (类模板特化) |