C++ forward_list 庫 - sort() 函式



描述

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

宣告

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

C++11

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

引數

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

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

返回值

異常

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

時間複雜度

線性,即 O(n)

示例

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

#include <iostream>
#include <forward_list>

using namespace std;

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

int main(void) {

   forward_list<int> fl = {1, 4, 2, 5, 3};

   cout << "List contents before sorting" << endl;
   for (auto it = fl.begin(); it != fl.end(); ++it)
      cout << *it << endl;

   fl.sort(cmp_fun);

   cout << "List contents after sorting" << endl;
   for (auto it = fl.begin(); it != fl.end(); ++it)
      cout << *it << endl;

   return 0;
}

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

List contents before sorting
1
4
2
5
3
List contents after sorting
5
4
3
2
1
forward_list.htm
廣告
© . All rights reserved.