如何对具有区分大小写元素的 std::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();
}
sort()
函数是否根据元素的字符代码对元素进行排序?我希望排序完成后这里的结果是 ab C
。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您想支持其他语言的字符,则不区分大小写的字符比较会很棘手。这就是为什么以区域设置敏感的方式执行它们是一个好主意:
这就是使用此类来比较两个字符的方式:
只需使用
std::locale()
作为my_locale
code> 如果您想使用默认设置的代码。如果你可以使用 Boost,那么字符串算法库中有一个 is_iless 函子可以做同样的事情。
借助
std::lexicographyal_compare
,将比较字符与字符串进行扩展很容易:现在您已拥有解决问题所需的一切:
Case-insensitive character comparisons are tricky if you want to support characters from other languages. That's why it's a good idea to do them in a locale-sensible manner:
This is how you use this class to compare two chars:
Just use
std::locale()
asmy_locale
if you want to use the one that's set as default.If you can use Boost then there is am
is_iless
functor in the String Algorithms library which does the same thing.Extending this from comparing chars to strings is easy thanks to
std::lexicographical_compare
:Now you have all that it's required to solve your problem:
默认比较器 (
<
) 使用默认的char_traits<; char >
会将您的列表排序为C a b
。请参阅list::sort。
为了达到所需的顺序
ab C
您可以:char_traits
,或提供自定义字符串比较器的实例
排序
,例如The default comparator (
<
) using the defaultchar_traits< char >
will sort your list asC a b
.See list::sort.
In order to achieve the desired order
a b C
you can either:string
types with customchar_traits
, orprovide an instance of a custom string comparator to
sort
, e.g.以下是我认为更干净、速度更快的替代方案:
Here are what I consider to be some cleaner and one significantly faster alternative:
yes
您可以检查以下代码以使用自定义比较器
yes
you can check the following code to use a custom comparator
从 C++11 开始,您还可以使用 lambda 表达式 而不是定义比较器函数/结构:
输出:
注:函数
strcasecmp()
(正如 @RobertS.Barnes 的回答中所建议的)不在 C++ 标准中,因此并非在每个系统上都可用。例如,如果您使用的是 Visual Studio,则可以使用_stricmp( )
代替。如果国际化对您来说是一个问题,那么您可以像 @Manuel 在他的回答中所做的那样应用区域设置。
Ideone 上的代码
Since C++11, you can also use a lambda expression instead of defining a comparator function/struct:
Output:
Note: The function
strcasecmp()
(as also suggested in the answer by @RobertS.Barnes) is not in the C++ standard and, therefore, not available on every system. For example, if you are using Visual Studio, you could use_stricmp()
instead.If internationalization is an issue for you, then you can apply a locale as @Manuel did in his answer.
Code on Ideone