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



描述

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

宣告

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

C++98

void sort();

引數

返回值

異常

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

時間複雜度

線性,即 O(n)

示例

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

#include <iostream>
#include <list>

using namespace std;

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;

   l.sort();

   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
1
2
3
4
5
list.htm
廣告