名稱空間
變體
操作

std::list<T,Allocator>::sort

來自 cppreference.com
< cpp‎ | 容器‎ | list
 
 
 
 
void sort();
(1)
template< class Compare >
void sort( Compare comp );
(2)

對元素進行排序並保持等價元素的順序。所有引用或迭代器都不會失效。

1) 元素使用 operator< 進行比較。
2) 元素使用 comp 進行比較。

如果丟擲異常,*this 中元素的順序未指定。

目錄

[編輯] 引數

comp - 比較函式物件(即滿足 Compare 要求的物件),如果第一個引數“小於”(即“排在第二個引數之前”)第二個引數,則返回 true

比較函式的簽名應等效於以下內容

bool cmp(const Type1& a, const Type2& b);

雖然簽名不需要包含 const&,但該函式不得修改傳遞給它的物件,並且必須能夠接受 Type1Type2 型別(可能為 const)的所有值,無論其 值類別如何(因此,不允許使用 Type1&,除非對於 Type1 移動等同於複製,否則也不允許使用 Type1(C++11 起))。
型別 Type1Type2 必須使得型別為 list<T,Allocator>::const_iterator 的物件可以被解引用,然後隱式轉換為這兩種型別。​

型別要求
-
Compare 必須滿足 Compare 的要求。

[編輯] 返回值

(無)

[編輯] 複雜度

給定 N 作為 size()

1) 大約 N·log(N) 次使用 operator< 的比較。
2) 大約 N·log(N) 次比較函式 comp 的應用。

[編輯] 注意

std::sort 需要隨機訪問迭代器,因此不能與 list 一起使用。此函式也與 std::sort 不同,它不要求 list 的元素型別可交換,保留所有迭代器的值,並執行穩定排序。

[編輯] 示例

#include <functional>
#include <iostream>
#include <list>
 
std::ostream& operator<<(std::ostream& ostr, const std::list<int>& list)
{
    for (const int i : list)
        ostr << ' ' << i;
    return ostr;
}
 
int main()
{
    std::list<int> list{8, 7, 5, 9, 0, 1, 3, 2, 6, 4};
    std::cout << "initially: " << list << '\n';
 
    list.sort();
    std::cout << "ascending: " << list << '\n';
 
    list.sort(std::greater<int>());
    std::cout << "descending:" << list << '\n';
}

輸出

initially:  8 7 5 9 0 1 3 2 6 4
ascending:  0 1 2 3 4 5 6 7 8 9
descending: 9 8 7 6 5 4 3 2 1 0

缺陷報告

下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。

缺陷報告 應用於 釋出時的行為 正確的行為
LWG 1207 C++98 迭代器和/或引用是否會失效不明確 保持有效

[編輯] 另請參閱

反轉元素的順序
(public 成員函式) [編輯]