Namespaces
Variants

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

From cppreference.net
ヘッダーで定義 <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) 文字シーケンス [ low1 , high1 ) を文字シーケンス [ low2 , high2 ) と、このロケールの照合規則を使用して比較し、最初の文字列が2番目の文字列の後に続く場合は 1 を、最初の文字列が2番目の文字列の前にある場合は - 1 を、2つの文字列が等価の場合はゼロを返します。

目次

パラメータ

low1 - 最初の文字列の先頭文字へのポインタ
high1 - 最初の文字列の終端次ポインタ
low2 - 2番目の文字列の先頭文字へのポインタ
high2 - 2番目の文字列の終端次ポインタ

戻り値

1 最初の文字列が2番目の文字列より大きい場合(照合順序で2番目の文字列の後に続く場合)、 - 1 最初の文字列が2番目の文字列より小さい場合(照合順序で2番目の文字列の前に来る場合)、2つの文字列が等価な場合はゼロを返します。

注記

三方比較が不要な場合(例えば Compare 引数を std::sort のような標準アルゴリズムに提供する場合など)、 std::locale::operator() の方がより適切かもしれません。

照合順序は辞書順です:文字の国語アルファベット内での位置(その 等価クラス )は、大文字小文字や異体字よりも優先されます。等価クラス内では、小文字は対応する大文字よりも前に照合され、アクセント記号付き文字にはロケール固有の順序が適用される場合があります。一部のロケールでは、文字のグループが単一の 照合単位 として比較されます。例えば、 "ch" はチェコ語では "h" の後、 "i" の前に位置し、 "dzs" はハンガリー語では "dz" の後、 "g" の前に位置します。

#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

関連項目

現在のロケールに従って2つの文字列を比較する
(関数)
現在のロケールに従って2つのワイド文字列を比較する
(関数)
このロケールの照合ファセットを使用して2つの文字列を辞書順に比較する
( std::locale の公開メンバ関数)