给定两个列表,我们必须将它们合并。
在这里,我们正在实现两个程序1)合并两个未排序的列表,2)合并两个排序的列表
示例
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
程序:
#include <iostream> #include <list> using namespace std; //显示列表的功能 void dispList(list<int> L) { //在列表中声明迭代器 list<int>::iterator l_iter; for (l_iter = L.begin(); l_iter != L.end(); l_iter++) cout<< *l_iter<< " "; cout<<endl; } int main(){ //声明列表 list<int> iList1 = {20, 10, 40, 30, 50}; list<int> iList2 = {90, 60, 50, 70, 80}; //打印列表元素 cout<<"List1 elements are"<<endl; dispList(iList1); cout<<"list2 elements are"<<endl; dispList(iList2); //将list2合并到list1- iList1.merge(iList2); cout<<"Merged list elements are"<<endl; dispList(iList1); return 0; }
输出结果
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