使用std :: sort排序std :: list [英] sorting std::lists using std::sort

查看:1096
本文介绍了使用std :: sort排序std :: list的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
使用stl排序功能对列表进行排序
为什么只有std :: list :: sort()?

Possible Duplicate:
Sort list using stl sort function
why only std::list::sort()?

我的问题是我们可以使用std :: sort函数对两个std :: list进行排序吗?我有2个字符串列表

My question is can we sort two std::lists using std::sort function? I have 2 string lists

  std::list<std::string>list1, list2;
  .....//entering values to list
  std::sort(list1.begin(), list1.end());

  std::sort(list2.begin(), list2.end());

当我对这些列表进行排序时,出现错误. 我尝试使用std :: vector,这时排序有效.

while i am sorting these lists i am getting error. I tried with std::vector, at this time the sort works.

错误就像

C:\ Program Files(x86)\ Microsoft Visual Studio 10.0 \ VC \ include \ xutility(1158): 参见"std :: operator-"的声明 1> C:\ Program Files(x86)\ Microsoft Visual Studio 10.0 \ VC \ include \ algorithm(3642): 错误C2784:'_Base1 :: difference_type std :: operator- (const std :: _ Revranit< _RanIt,_Base>&,const std :: _ Revranit< _RanIt2,_Base2>&)'): 无法推断出'const std :: _ Revranit< _RanIt,_Base>&'的模板参数 来自"std :: _ List_iterator< _Mylist>" 1>与 1> [ 1> _Mylist = std :: _ List_val> 1>]

C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\xutility(1158) : see declaration of 'std::operator -' 1>C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\algorithm(3642): error C2784: '_Base1::difference_type std::operator - (const std::_Revranit<_RanIt,_Base> &,const std::_Revranit<_RanIt2,_Base2> &)' : could not deduce template argument for 'const std::_Revranit<_RanIt,_Base> &' from 'std::_List_iterator<_Mylist>' 1> with 1> [ 1> _Mylist=std::_List_val> 1> ]

我必须知道只有std :: sort支持列表?

I have to know that only std::sort supports lists?

推荐答案

您不能使用std::sortstd::list进行排序,因为std::sort要求迭代器是随机访问的,并且std::list迭代器仅是双向的

You can't use std::sort to sort std::list, because std::sort requires iterators to be random access, and std::list iterators are only bidirectional.

但是,std::list具有成员函数sort对其进行排序:

However, std::list has a member function sort that will sort it:

list.sort();
// if you want to use a comparator different from the default one:
// list.sort(comparator);

这篇关于使用std :: sort排序std :: list的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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