名稱空間
變體
操作

std::collate<CharT>::compare, std::collate<CharT>::do_compare

來自 cppreference.com
< cpp‎ | locale‎ | collate
 
 
 
 
 
定義於標頭檔案 <locale>
public:

int compare( const CharT* low1, const CharT* high1,

             const CharT* low2, const CharT* high2 ) const;
(1)
protected:

virtual int do_compare( const CharT* low1, const CharT* high1,

                        const CharT* low2, const CharT* high2 ) const;
(2)
1) 公有成員函式,呼叫派生程度最高的類中的保護虛成員函式 do_compare
2) 使用此區域設定的排序規則,比較字元序列 [low1high1) 與字元序列 [low2high2),如果第一個字串在第二個字串之後,則返回 1,如果第一個字串在第二個字串之前,則返回 -1,如果兩個字串等價,則返回零。

目錄

[edit] 引數

low1 - 指向第一個字串的第一個字元的指標
high1 - 第一個字串的結束指標之後一位
low2 - 指向第二個字串的第一個字元的指標
high2 - 第二個字串的結束指標之後一位

[edit] 返回值

如果第一個字串大於第二個字串(即在排序順序中位於第二個字串之後),則返回 1,如果第一個字串小於第二個字串(在排序順序中位於第二個字串之前),則返回 -1,如果兩個字串等價,則返回零。

[edit] 注意

當不需要三路比較時(例如,在為標準演算法(如 std::sort)提供 Compare 引數時),std::locale::operator() 可能更合適。

排序順序是字典順序:字母在國家字母表中的位置(其等價類)具有比其大小寫或變體更高的優先順序。在等價類中,小寫字元在它們的大寫對應物之前排序,並且特定於區域設定的順序可能適用於帶變音符號的字元。在某些區域設定中,字元組作為單個排序單元進行比較。例如,捷克語中的 "ch""h" 之後,在 "i" 之前;匈牙利語中的 "dzs""dz" 之後,在 "g" 之前。

[edit] 示例

#include <iostream>
#include <locale>
#include <string>
 
template<typename CharT>
void try_compare(const std::locale& l, const CharT* p1, const CharT* p2)
{
    auto& f = std::use_facet<std::collate<CharT>>(l);
 
    std::basic_string<CharT> s1(p1), s2(p2);
    if (f.compare(&s1[0], &s1[0] + s1.size(),
                  &s2[0], &s2[0] + s2.size()) < 0)
        std::wcout << p1 << " before " << p2 << '\n';
    else
        std::wcout << p2 << " before " << p1 << '\n';
}
 
int main()
{
    std::locale::global(std::locale("en_US.utf8"));
    std::wcout.imbue(std::locale());
 
    std::wcout << "In the American locale: ";
    try_compare(std::locale(), "hrnec", "chrt");
    std::wcout << "In the Czech locale: ";
    try_compare(std::locale("cs_CZ.utf8"), "hrnec", "chrt");
 
    std::wcout << "In the American locale: ";
    try_compare(std::locale(), L"år", L"ängel");
    std::wcout << "In the Swedish locale: ";
    try_compare(std::locale("sv_SE.utf8"), L"år", L"ängel");
}

輸出

In the American locale: chrt before hrnec
In the Czech locale: hrnec before chrt
In the American locale: ängel before år
In the Swedish locale: år before ängel

[edit] 參閱

根據當前區域設定比較兩個字串
(函式) [編輯]
根據當前語言環境比較兩個寬字串
(函式) [編輯]
使用此區域設定的 collate facet 對兩個字串進行字典比較
(std::locale 的公有成員函式) [編輯]