我試圖以區域設置相關的方式比較std::string
。std :: string的區域設置相關排序
對於普通的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
代碼,因此它感覺不對。
有沒有辦法讓這種排序方式爲字符串以無縫方式工作?
這很方便。它使標準館藏無需工作。 – CAdaker 2009-08-31 14:12:04