std::forward_list<T,Allocator>::sort
來自 cppreference.com
< cpp | 容器 | forward_list
void sort(); |
(1) | (C++11 起) |
template< class Compare > void sort( Compare comp ); |
(2) | (C++11 起) |
對元素進行排序並保留等效元素的順序。沒有引用或迭代器會失效。
1) 使用 operator< 比較元素。
2) 使用 comp 比較元素。
如果丟擲異常,則 *this 中元素的順序未指定。
目錄 |
[編輯] 引數
comp | - | 比較函式物件(即滿足 Compare 要求的物件),如果第一個引數“小於”(即“排在”第二個引數之前),則返回 true。 比較函式的簽名應等效於以下內容 bool cmp(const Type1& a, const Type2& b); 雖然簽名不需要包含 const&,但函式不得修改傳遞給它的物件,並且必須能夠接受 |
型別要求 | ||
-Compare 必須滿足 Compare 的要求。 |
[編輯] 返回值
(無)
[編輯] 複雜度
給定 N 為 std::distance(begin(), end())
1) 使用 operator< 進行大約 N·log(N) 次比較。
2) 大約 N·log(N) 次應用比較函式 comp。
[編輯] 注意
std::sort 需要隨機訪問迭代器,因此不能與 forward_list
一起使用。此函式與 std::sort 的不同之處在於,它不要求 forward_list
的元素型別是可交換的,它會保留所有迭代器的值,並執行穩定的排序。
[編輯] 示例
執行此程式碼
#include <functional> #include <iostream> #include <forward_list> std::ostream& operator<<(std::ostream& ostr, const std::forward_list<int>& list) { for (const int i : list) ostr << ' ' << i; return ostr; } int main() { std::forward_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
[編輯] 參閱
反轉元素的順序 (public member function) |