名稱空間
變體
操作

std::collate<CharT>::hash, std::collate<CharT>::do_hash

來自 cppreference.com
< cpp‎ | locale‎ | collate
 
 
 
 
 
定義於標頭檔案 <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 方面可能會提供不同的排序規則,例如,如果字串具有相同的 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

[編輯] 參閱

字串的雜湊支援
(類模板特化) [編輯]