使用std :: sort排序std :: list [英] sorting std::lists using std::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::sort
对std::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屋!