List Merge Function - C++ Programming Tutorial
C++ Course / Dynamic Programming / List Merge Function

List Merge Function

BLUF: Mastering List Merge Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: List Merge Function

C++ is renowned for its efficiency. Learn how List Merge Function enables low-level control and high-performance computing in the tutorial below.

C++ List merge

The merge function in C++ combines two sorted lists in ascending order. It integrates the second list into the specified list container, resulting in the removal of all elements from the second list.

Two condition can be ocurred in merge function:

If a comparator is not provided as a parameter, the function will merge the two sorted lists into a single list.

If a comparator is provided as a parameter, the merging of the list is determined by their internal comparisons.

Syntax

Consider two arrays named list1 and list2. The syntax is as follows:

Example

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

Parameter

list2 : The list to be merged with the list1.

It is a comparison function object that evaluates the value of the initial argument against the second argument. If the initial argument's value is lower than the second argument, it will output true; otherwise, it will output 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 instance, the merge function combines the li list with the li1 list into a unified list.

Example 2

Let's examine a basic scenario where the comparator is provided as a 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 instance, the merge function combines the list by utilizing internal comparisons.

Input Required

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

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience