forward_list merge() in C++ STL

forward_list::merge() is an inbuilt function in C++ STL which merges two sorted forward_lists into one.
The merge() function can be used in two ways:

  1. Merge two forward lists that are sorted in ascending order into one.
  2. Merge two forward lists into one using a comparison function.

Syntax:

forwardlist_name1.merge(forward_list& forwardlist_name2)
                  or
forwardlist_name1.merge(forward_list& forwardlist_name2, Compare comp)

Parameters: The function accepts two parameters which are specified as below:

  1. forwardlist_name2 – Another forward list of the same type which is to be merged
  2. comp – A comparison function which should return true or false.

Return value: The function does not return anything.
Below programs illustrate the above function:
Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to illustrate the
// forward_list::merge() function
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    forward_list<int> fl1 = { 12, 25, 31, 41 };
    forward_list<int> fl2 = { 10, 20, 30 };
  
    // merge two forward list
    fl1.merge(fl2);
  
    // print the contents of the forward list
    cout << "List contains following elements" << endl;
    for (auto it = fl1.begin(); it != fl1.end(); ++it)
        cout << *it << " ";
  
    return 0;
}

chevron_right


Output:

List contains following elements
10 12 20 25 30 31 41


Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <bits/stdc++.h>
using namespace std;
  
// comparison function
bool cmp_fun(int a, int b)
{
    return a > b;
}
  
int main()
{
    forward_list<int> fl1 = { 41, 31, 25, 12 };
    forward_list<int> fl2 = { 30, 20, 10 };
  
    // merge two forward list
    fl1.merge(fl2, cmp_fun);
  
    // print the contents of the forward list
    cout << "List contains following elements" << endl;
    for (auto it = fl1.begin(); it != fl1.end(); ++it)
        cout << *it << " ";
  
    return 0;
}

chevron_right


Output:

List contains following elements
41 31 30 25 20 12 10


My Personal Notes arrow_drop_up

Coder Machine Learner Social Activist Vocalist

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.