cpx*_*cpx 3 c++ sorting stl list
这是我目前的代码:
#include <list>
#include <string>
using std::string;
using std::list;
int main()
{
list <string> list_;
list_.push_back("C");
list_.push_back("a");
list_.push_back("b");
list_.sort();
}
Run Code Online (Sandbox Code Playgroud)
该sort()
函数是否根据字符代码对元素进行排序?我希望这里的结果是a b C
在排序完成之后.
如果要支持其他语言的字符,则不区分大小写的字符比较很棘手.这就是为什么以区域性合理的方式做到这一点是个好主意:
struct char_iless
: public std::binary_function<char, char, bool>
{
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);
}
};
Run Code Online (Sandbox Code Playgroud)
这是你使用这个类来比较两个字符的方法:
char_iless('a', 'b', my_locale);
Run Code Online (Sandbox Code Playgroud)
只需使用std::locale()
,就my_locale
好像你想使用默认设置的那个.
如果你可以使用Boost那么is_iless
在String Algorithms库中有一个functor,它可以做同样的事情.
从比较字符到字符串扩展这一点很简单,这要归功于std::lexicographical_compare
:
struct str_iless
: public std::binary_function<std::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)
);
}
};
Run Code Online (Sandbox Code Playgroud)
现在,您已经拥有了解决问题所需的一切:
int main()
{
std::list<std::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));
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2524 次 |
最近记录: |