不区分大小写的字符比较是棘手。这就是为什么它是一个好主意,做他们在一个区域,合理的方式:
struct char_iless
: public std::binary_function
{
std::locale loc;
char_iless(std::locale const & loc=std::locale()) : loc(loc)
{
}
bool operator()(char a, char b) const
{
return std::tolower(a, loc) < std::tolower(b, loc);
}
};
这是你如何使用这个类来比较两个字符:
char_iless('a', 'b', my_locale);
只需使用std::locale()作为my_locale如果你想使用默认设置的那个。
如果你可以使用Boost,那么在字符串算法库中有is_iless函子,它可以做同样的事情。
从字符比较字符串扩展,这是容易由于std::lexicographical_compare:
struct str_iless
: public std::binary_function<:string std::string bool>
{
std::locale loc;
str_iless(std::locale const & loc=std::locale()) : loc(loc)
{
}
bool operator()(std::string const & a, std::string const & b) const
{
return std::lexicographical_compare(
a.begin(), a.end(),
b.begin(), b.end(),
char_iless(loc)
);
}
};
现在,你拥有所有,它的要求来解决问题:
int main()
{
std::list<:string> list;
list.push_back("C");
list.push_back("a");
list.push_back("b");
// Sort using default locale
list.sort(str_iless());
// Sort using French locale
// (warning: this locale format string is MS specific)
std::locale loc("French_France.1252");
list.sort(str_iless(loc));
}