In this article, we will discuss the forward_list merge function in C++ with its syntax, example.
A forward list is a sequence container that allows constant time insert and erase operations wherever in the sequence. Forward lists are created using singly linked lists. The ordering is maintained by associating each element with a link to the following element in the sequence.
What is the function forward_list::merge?
The forwardlist::merge is a built-in C++ STL function that is declared in the header file. It can merge two sorted forwardlists into one using the merge function. In other words, the merge function is used to combine two sorted forward_lists into a single one.
We need to verify that the two lists are in order of sort before combining them. If no comparator is provided, it combines two lists into a single sorted list. When we want to do internal evaluations between two lists, we must provide a comparator.
Syntax:
It has the following syntax:
flist_contain1.merge(flist_contain2); //merging lists
flist_contain1.merge(flist_contain2, comparator);
This function accepts one or two arguments:
list_contain2: It represents the object of the second list that will be merged.
Comparator: It specifies an internal comparison. It is a binary predicate with two inputs of the same value that are specified in the list container; it returns true if the listcontain1 element has been determined to come before the listcontain2 element. Otherwise, it returns false.
Example:
Let us take a C++ program to illustrate the use of forward_list merge function.
// CPP application demonstrating the forward_list::merge() method
#include <bits/stdc++.h>
using namespace std;
int main()
{
forward_list<int> flist1 = { 11, 35, 45, 67 };
forward_list<int> flist2 = { 30, 40, 50 };
// merging of two lists
flist1.merge(flist2);
// display result
cout << "The elements of the list are:" << endl;
for (auto ite = flist1.begin(); ite != flist1.end(); ++ite)
cout << *ite << " ";
return 0;
}
Output:
The elements of the list are:
11 30 35 40 45 50 67
Example 2:
Let us take another C++ program to illustrate the use of forward_list merge function.
// CPP application demonstrating the forward_list::merge() method
#include <bits/stdc++.h>
using namespace std;
// function for comparing
bool cmp_fun(int a, int b)
{
return a > b;
}
int main()
{
forward_list<int> flist1 = { 20, 24, 38, 45 };
forward_list<int> flist2 = { 21, 39, 11 };
// merging the two lists
flist1.merge(flist2, cmp_fun);
//displaying the result
cout << "The elements of the lists are:" << endl;
for (auto ite = flist1.begin(); ite != flist1.end(); ++ite)
cout << *ite << " ";
return 0;
}
Output:
The elements of the lists are:
21 39 20 24 38 45 11