sorting std::lists using std::sort [duplicate]

六月ゝ 毕业季﹏ 提交于 2020-01-13 07:52:11

问题


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

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());

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

The error is like

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> ]

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


回答1:


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.

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);



回答2:


You should use list::sort, which may use a different algorithm. std::sort requires random-access iterators (supporting jumps of arbitrary size) whereas list iterators can only go forwards or backwards by one link at a time.

See C++11 25.4.1.1:

template<class RandomAccessIterator> void sort(RandomAccessIterator first, 
         RandomAccessIterator last);

and 23.3.5.5/27 (members of std::list):

void sort();
template <class Compare> void sort(Compare comp);


来源:https://stackoverflow.com/questions/10652674/sorting-stdlists-using-stdsort

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!