9

std::stringロケールに依存する方法で sを比較しようとしています。

通常のCスタイルの文字列の場合strcoll、実行した後、まさに私が望むことを行う を見つけましたstd::setlocale

#include <iostream>
#include <locale>
#include <cstring>

bool cmp(const char* a, const char* b)
{
    return strcoll(a, b) < 0;
}

int main()
{
    const char* s1 = "z", *s2 = "å", *s3 = "ä", *s4 = "ö";

    std::cout << (cmp(s1,s2) && cmp(s2,s3) && cmp(s3,s4)) << "\n"; //Outputs 0
    std::setlocale(LC_ALL, "sv_SE.UTF-8");
    std::cout << (cmp(s1,s2) && cmp(s2,s3) && cmp(s3,s4)) << "\n"; //Outputs 1, like it should

    return 0;
}

ただし、この動作も同様に行いたいと思いstd::stringます。私はオーバーロードoperator<して次のようなことをすることができました

bool operator<(const std::string& a, const std::string& b)
{
    return strcoll(a.c_str(), b.c_str());
}

std::lessしかし、その後、 andを使用するコードについて心配する必要がstd::string::compareあるため、適切ではありません。

この種の照合を文字列に対してシームレスに機能させる方法はありますか?

4

4 に答える 4

8

std::locale の operator() はまさにあなたが探しているものです。現在のグローバル ロケールを取得するには、デフォルトのコンストラクターを使用します。

于 2009-08-31T13:11:53.850 に答える
6

C++ ライブラリは、ロケール固有の照合を行うためのcollat​​e ファセットを提供します。

于 2009-08-31T13:16:32.533 に答える
0

少し調べてみると、それを行う1つの方法は、std::basic_stringテンプレートをオーバーロードして、新しいローカライズされた文字列クラスを作成することである可能性があることに気付きました。

これにはおそらく数え切れないほどのバグがありますが、概念実証として:

#include <iostream>
#include <locale>
#include <string>

struct localed_traits: public std::char_traits<wchar_t>
{
    static bool lt(wchar_t a, wchar_t b)
    {
        const std::collate<wchar_t>& coll =
            std::use_facet< std::collate<wchar_t> >(std::locale());
        return coll.compare(&a, &a+1, &b, &b+1) < 0;
    }

    static int compare(const wchar_t* a, const wchar_t* b, size_t n)
    {
        const std::collate<wchar_t>& coll =
            std::use_facet< std::collate<wchar_t> >(std::locale());
        return coll.compare(a, a+n, b, b+n);
    }
};

typedef std::basic_string<wchar_t, localed_traits> localed_string;

int main()
{
    localed_string s1 = L"z", s2 = L"å", s3 = L"ä", s4 = L"ö";

    std::cout << (s1 < s2 && s2 < s3 && s3 < s4 ) << "\n"; //Outputs 0
    std::locale::global(std::locale("sv_SE.UTF-8"));
    std::cout << (s1 < s2 && s2 < s3 && s3 < s4 ) << "\n"; //Outputs 1

    return 0;
}

charしかし、代わりにそれをベースにするとうまくいかないようで、理由はわかりませんwchar_t...

于 2009-08-31T14:09:48.147 に答える
-1

C++ では、標準の照合ファセットを使用する必要があります。それをチェックしてください

于 2009-08-31T13:49:23.133 に答える