std::collate<CharT>:: hash, std::collate<CharT>:: do_hash
From cppreference.net
|
定义于头文件
<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 | - | 指向待哈希序列结束位置后一位的指针 |
返回值
遵循排序规则的哈希值。
说明
系统提供的区域设置通常不会将两个字符串视为等价( compare() 不会返回 0 ),如果 basic_string::operator== 返回 false 。但用户安装的 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)
|
字符串的哈希支持
(类模板特化) |