【发布时间】:2009-08-31 13:05:07
【问题描述】:
我正在尝试以依赖于语言环境的方式比较 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
和std::string::compare
的代码,所以感觉不对。
有没有办法让这种排序规则无缝地适用于字符串?
【问题讨论】: