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:
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
#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:
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.
#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:
5 6 7 9 10 11 15
In this instance, the merge function combines the list by utilizing internal comparisons.