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



描述

C++ 函式std::list::merge()將兩個已排序的列表合併為一個。

宣告

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

C++98

template <class Compare>
void merge (list& x, Compare comp);

C++11

template <class Compare>
void merge (list& x, Compare comp);

引數

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

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

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

返回值

無。

異常

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

時間複雜度

線性,即 O(n)

示例

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

#include <iostream>
#include <list>

using namespace std;

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

int main(void) {
   list<int> l1 = {31, 11, 5, 1};
   list<int> l2 = {30, 20, 10};

   l2.merge(l1, cmp_fun);

   cout << "List contains following elements after merge operation" << endl;

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

   return 0;
}

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

List contains following elements after merge operation
31
30
20
11
10
5
1
list.htm
廣告

© . All rights reserved.