std :: string的语言环境相关排序

CAd*_*ker 9 c++ string locale

我试图以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;
}
Run Code Online (Sandbox Code Playgroud)

但是,我也希望有这种行为std::string.我可以过载operator<来做类似的事情

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

但后来我不得不担心代码使用std::lessstd::string::compare,所以感觉不对.

有没有办法让这种校对以无缝方式为字符串工作?

APr*_*mer 8

std :: locale的operator()就是您正在搜索的内容.要获取当前的全局区域设置,只需使用默认构造函数.


Mar*_*wis 6

C++库提供collat​​e facet以进行特定于语言环境的排序规则.