C++ List Library - merge() Function


Advertisements

Description

The C++ function std::list::merge() merges two sorted lists into one.

Declaration

Following is the declaration for std::list::merge() function form std::list header.

C++98

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

C++11

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

Parameters

  • x − Another list object of same type.

  • comp − A comparison function which should return true or false. It has following prototype.

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

Return value

None.

Exceptions

This member function never throws exception.

Time complexity

Linear i.e. O(n)

Example

The following example shows the usage of std::list::merge() function.

#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;
}

Let us compile and run the above program, this will produce the following result −

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