如何排序带有区分大小写元素的std :: list? [英] How can I sort a std::list with case sensitive elements?

查看:57
本文介绍了如何排序带有区分大小写元素的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()函数是否根据元素的字符代码对元素进行排序?我希望排序后的结果是a b C.

Does the sort() function sort the elements according to their character codes? I want the result here to be a b C after the sorting is done.

推荐答案

使用默认char_traits< char >的默认比较器(<)将您的列表排序为C a b.

The default comparator (<) using the default char_traits< char > will sort your list as C a b.

请参见 list :: sort .

为了获得所需的订单a b C,您可以:

In order to achieve the desired order a b C you can either:

  1. 使用自定义char_traits 组成string类型的列表
  2. sort提供自定义字符串比较器的实例,例如

  1. compose your list of string types with custom char_traits, or
  2. provide an instance of a custom string comparator to sort, e.g.

bool istring_less(const string& lhs, const string& rhs) {
  string::const_iterator \
    lb = lhs.begin(), le = lhs.end(),
    rb = rhs.begin(), re = rhs.end();
  const char lc, rc;
  for ( ; lb != le && rb != re; ++lb, ++rb) {
    lc = tolower(*lb);
    rc = tolower(*rb);
    if (*lc < *rc) return true;
    if (*lc > *rc) return false;
  }
  // if rhs is longer than lhs then lhs<rhs
  return (rb != re);
}
...
list.sort(istring_less);

这篇关于如何排序带有区分大小写元素的std :: list?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆