std :: string的语言环境依赖排序 [英] locale-dependent ordering for std::string

查看:103
本文介绍了std :: string的语言环境依赖排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图以区域设置的方式比较 std :: string

I am trying to compare std::strings in a locale-dependent manner.

C-style字符串,我发现 std :: setlocale 后,我找到了 strcoll

For ordinary C-style strings, I've found strcoll, which does exactly what I want, after doing 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 。我可以只是重载运算符<做一些像

However, I'd like to have this behaviour for std::string as well. I could just overload operator< to do something like

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

但是我不得不担心使用 std :: less std :: string :: compare ,所以感觉不对。

but then I'd have to worry about code using std::less and std::string::compare, so it doesn't feel right.

有没有办法使这种排序规则以无缝的方式用于字符串?

Is there a way to make this kind of collation work for strings in a seamless manner?

推荐答案

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

operator() of std::locale is just what you are searching. To get the current global locale, just use the default constructor.

这篇关于std :: string的语言环境依赖排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆