List Merge Function

C++ List merge

C++ List merge function merges two sorted list in an increasing order. It merges y list into the given list container and this removes all the elements from y.

Two condition can be ocurred in merge function:

If the comparator is not passed in the parameter then the two sorted list is merged into a single one.

If the comparator is passed in the parameter then the list is merged based on their internal comparisons.

Syntax

Consider two list list1 and list2. Syntax would be:

Example

list1.merge(list2);
list1.merge(list2,compare);

Parameter

list2 : The list to be merged with the list1.

compare : It is a compare function object that compares the value of the first argument with the second argument. If the value of the first argument is less than the second argument then it returns true otherwise false.

Return value

It does not return any value.

Example 1

Let's see a simple example

Example

#include <iostream>
#include<list>
using namespace std;
int main()
{
   list<int> li={1,2,3,4};
   list<int> li1={5,6,7,8};
   li.merge(li1);
   for(list<int>::iterator itr=li.begin();itr!=li.end();++itr)
   std::cout << *itr<<? ?;
    return 0;
}

Output:

Output

1 2 3 4 5 6 7 8

In this example, merge function merges the list li with the list li1 in a single list.

Example 2

Let's see a simple example when the comparator is passed in the parameter

Example

#include <iostream>
#include<list>
using namespace std;
bool comparison(int first, int second)
{
    bool a;
    a=first<second;
    return (a);
}
int main()
{
  list<int> li={9,10,11};
  list<int> li1={5,6,7,15};
  li.merge(li1,comparison);
  for(list<int>::iterator itr=li.begin();itr!=li.end();++itr)
  std::cout << *itr <<" "<< std::endl;
  return 0;
}

Output:

Output

5 6 7 9 10 11 15

In this example, merge function merges the list based on the internal comparisons.

Input Required

This code uses input(). Please provide values below: