Merge two lists using merge() function | C++ STL

Example of merge() function in C++ STL: Here, we are going to learn how to merge two lists using merge() function in C++ STL program?
Submitted by IncludeHelp, on October 31, 2018

Given two lists and we have to merge them.

Here, we are implementing two programs 1) to merge two unsorted lists and 2) to merge two sorted lists

1 ) Merge two unsorted lists

Example:

    Input: 
    list1: {20, 10, 40, 30, 50}
    list2: {90, 60, 50, 70, 80}
    
    Output: 
    Merged list:
    20 10 40 30 50 90 60 50 70 80

Program:

#include <iostream>
#include <list>
using namespace std;

//function to display the list 
void dispList(list<int> L)
{
	//declaring iterator to the list 
	list<int>::iterator l_iter;
	for (l_iter = L.begin(); l_iter != L.end(); l_iter++)
		cout<< *l_iter<< " ";
	cout<<endl;
}

int main()
{
	//declaring a list 
	list<int> iList1 = {20, 10, 40, 30, 50};
	list<int> iList2 = {90, 60, 50, 70, 80};

	//printing list elements
	cout<<"List1 elements are"<<endl;
	dispList(iList1);
	cout<<"list2 elements are"<<endl;
	dispList(iList2);

	//merging list2 into list1 
	iList1.merge(iList2);

	cout<<"Merged list elements are"<<endl;
	dispList(iList1);

	return 0;
}

Output

List1 elements are
20 10 40 30 50
list2 elements are
90 60 50 70 80
Merged list elements are
20 10 40 30 50 90 60 50 70 80

2) Merge two sorted lists

Example:

    Input:
    list1: {20, 10, 40, 30, 50}
    list2: {90, 60, 50, 70, 80}

    Output:
    List1 elements are
    20 10 40 30 50
    list2 elements are
    90 60 50 70 80

    //sorting the lists 
    List1 (sorted) elements are
    10 20 30 40 50
    List2 (sorted) elements are
    50 60 70 80 90

    Merged list elements are
    10 20 30 40 50 50 60 70 80 90

Program:

#include <iostream>
#include <list>
using namespace std;

//function to display the list 
void dispList(list<int> L)
{
	//declaring iterator to the list 
	list<int>::iterator l_iter;
	for (l_iter = L.begin(); l_iter != L.end(); l_iter++)
		cout<< *l_iter<< " ";
	cout<<endl;
}

int main()
{
	//declaring a list 
	list<int> iList1 = {20, 10, 40, 30, 50};
	list<int> iList2 = {90, 60, 50, 70, 80};

	//printing list elements
	cout<<"List1 elements are"<<endl;
	dispList(iList1);
	cout<<"list2 elements are"<<endl;
	dispList(iList2);

	//sort the lists
	iList1.sort();
	iList2.sort();

	//printing sorted list elements
	cout<<"List1 (sorted) elements are"<<endl;
	dispList(iList1);
	cout<<"List2 (sorted) elements are"<<endl;
	dispList(iList2);

	//merging list2 into list1 
	iList1.merge(iList2);

	cout<<"Merged list elements are"<<endl;
	dispList(iList1);

	return 0;
}

Output

List1 elements are
20 10 40 30 50
list2 elements are
90 60 50 70 80
List1 (sorted) elements are
10 20 30 40 50
List2 (sorted) elements are
50 60 70 80 90
Merged list elements are
10 20 30 40 50 50 60 70 80 90



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.