2012-05-18 38 views
8

可能重複:
Sort list using stl sort function
why only std::list::sort()?使用std ::排序的std ::列表進行排序

我的問題是,我們才能排序2名的std ::使用std列表排序::功能?我有2個字符串列表

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

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

雖然我排序這些名單我得到錯誤。 我試過用std :: vector,此時排序工作。

的錯誤是像

C:\ Program Files文件(x86)的\微軟的Visual Studio 10.0 \ VC \ \包括xutility(1158): 看到的宣言 '的std ::運營商 - ' 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> &)': 無法推導出'const std :: _ Revranit的模板參數< _RanIt,_base> &' 從 '的std :: _ List_iterator < _Mylist>' 1>使用 1> [ 1> _Mylist =標準:: _ List_val> 1>]

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

+0

超載的<經營者爲對象(如果它尚未定義),使用std ::排序。 – Martol1ni

+0

[爲什麼只有std :: list :: sort()?](http://stackoverflow.com/questions/7996116/why-only-stdlistsort)和[使用stl sort函數排序列表](http:/ /stackoverflow.com/questions/2432857/sort-list-using-stl-sort-function) –

+0

@ Martol1ni:它是'std :: string'。 'operator <'被定義,但它不會幫助。 –

回答

37

不能使用std::sort排序std::list,因爲std::sort要求迭代器是隨機訪問,並且迭代器只是雙向的。

然而,std::list有一個成員函數sort,將對其進行排序:

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

您應該使用list::sort,它可能會使用不同的算法。 std::sort需要隨機訪問迭代器(支持任意大小的跳轉),而列表迭代器一次只能通過一個鏈接前進或後退。

見C++ 11 25.4.1.1:

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

和23.3.5.5/27(的std::list成員):

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