C++ List Library - merge() Function


Advertisements

Description

The C++ function std::list::merge() merges two sorted lists into one. The lists should be sorted in ascending order.

Declaration

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

C++98

void merge (list& x);

C++11

void merge (list& x);

Parameters

x − Another list object of same type.

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;

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

   l2.merge(l1);

   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
1
5
10
11
20
30
31
list.htm
Advertisements