C++ forward_list 庫 - merge() 函式



描述

C++ 函式std::forward_list::merge() 將兩個已排序的 forward_list 合併成一個。

宣告

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

C++11

template <class Compare>
void merge (forward_list& fwdlst, Compare comp);

引數

  • x - 另一個相同型別的 forward_list 物件。

  • comp - 一個比較函式,應該返回 true 或 false。它具有以下原型。

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

返回值

異常

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

時間複雜度

線性,即 O(n)

示例

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

#include <iostream>
#include <forward_list>

using namespace std;

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

int main(void) {

   forward_list<int> fl1 = {31, 11, 5, 1};
   forward_list<int> fl2 = {30, 20, 10};

   fl2.merge(fl1, cmp_fun);

   cout << "List contains following elements" << endl;

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

   return 0;
}

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

List contains following elements
31
30
20
11
10
5
1
forward_list.htm
廣告
© . All rights reserved.