C++ 列表庫 - sort() 函式



描述

C++ 函式std::list::sort() 對列表中的元素進行排序。相等元素的順序保持不變。它使用比較函式來比較值。

宣告

以下是來自 std::list 標頭檔案的 std::list::sort() 函式的宣告。

C++98

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

引數

comp - 返回布林值的比較函式物件。它具有以下原型。

bool cmp(const Type1 &ar1, const Type2 &arg2);

返回值

異常

此成員函式從不丟擲異常。

時間複雜度

線性,即 O(n)

示例

以下示例顯示了 std::list::sort() 函式的使用方法。

#include <iostream>
#include <list>

using namespace std;

bool comp(int a, int b) {
   return (a > b);
}

int main(void) {
   list<int> l = {1, 4, 2, 5, 3};

   cout << "Contents of list before sort operation" << endl;

   for (auto it = l.begin(); it != l.end(); ++it)
      cout << *it << endl;

   /* Descending sort */
   l.sort(comp);

   cout << "Contents of list after sort operation" << endl;

   for (auto it = l.begin(); it != l.end(); ++it)
      cout << *it << endl;

   return 0;
}

讓我們編譯並執行以上程式,這將產生以下結果:

Contents of list before sort operation
1
4
2
5
3
Contents of list after sort operation
5
4
3
2
1
list.htm
廣告

© . All rights reserved.