C++ STL list, merge() program example

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Using the C++ merge() to remove the elements from the argument list, inserts them into the target list, and orders the new, combined set of elements in ascending order or in some other specified order in C++ programming

To show: How to use the C++ list, merge() to remove the elements from the argument list, inserts them into the target list, and orders the new, combined set of elements in ascending order or in some other specified order in C++ programming

 

// C++ STL list, merge()

#include <list>

#include <iostream>

using namespace std;

 

int main(void)

{

// containers

list <int> con1, con2, con3;

// iterators

list <int>::iterator con1_Iter, con2_Iter, con3_Iter;

 

// the data must be in order, inserting/pushing data into list

con1.push_back(3);

con1.push_back(6);

con2.push_back(2);

con2.push_back(4);

con3.push_back(5);

con3.push_back(1);

 

// print the data

cout<<"con1 list: ";

for (con1_Iter = con1.begin(); con1_Iter != con1.end(); con1_Iter++)

cout<<" "<<*con1_Iter;

cout<<endl;

cout<<"con2 list: ";

for(con2_Iter = con2.begin(); con2_Iter != con2.end(); con2_Iter++)

cout<<" "<<*con2_Iter;

cout<<endl;

// merging con1 into con2 in (default) ascending order

con2.merge(con1);

con2.sort(greater<int>());

cout<<"After merging con1 with con2 and sorting with >, con2 list: ";

for (con2_Iter = con2.begin(); con2_Iter != con2.end(); con2_Iter++)

cout<<" "<<*con2_Iter;

cout<<endl;

cout<<"\ncon3 list: ";

for (con3_Iter = con3.begin(); con3_Iter != con3.end(); con3_Iter++)

cout<<" "<<*con3_Iter;

cout<<endl;

con2.merge(con3, greater<int>( ));

cout<<"After merging con3 with con2 according to the '>' comparison relation, con2 list: ";

for (con2_Iter = con2.begin(); con2_Iter != con2.end(); con2_Iter++)

cout<<" "<<*con2_Iter;

cout<<endl;

return 0;

}

 

Output examples:

 

con1 list: 3 6

con2 list: 2 4

After merging con1 with con2 and sorting with >, con2 list: 6 4 3 2

con3 list: 5 1

After merging con3 with con2 according to the '>' comparison relation, con2 list: 6 5 4 3 2 1

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index