Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two lists c++

Tags:

c++

c++11

I want to merge two lists such that only one entry of common element is present in the merged queue.

std::list<int> list1 = { 5,9,0,1,3,4 };
std::list<int> list2 = { 8,7,2,6,4 }; 
list1.sort();
list2.sort();
std::cout << "list1:  " << list1 << "\n";
std::cout << "list2:  " << list2 << "\n";
list1.merge(list2);
std::cout << "merged: " << list1 << "\n";

The output looks like:

list1:   0 1 3 4 5 9
list2:   2 4 6 7 8
merged:  0 1 2 3 4 4 5 6 7 8 9

I want the output to look like:

list1:   0 1 3 4 5 9
list2:   2 4 6 7 8
merged:  0 1 2 3 4 5 6 7 8 9
like image 780
Namitha Avatar asked Dec 14 '22 10:12

Namitha


1 Answers

list1.sort();
list1.unique();

since your list is sorted just call unique

list1.unique();

your full code:

std::list<int> list1 = { 5,9,0,1,3,4 };
std::list<int> list2 = { 8,7,2,6,4 }; 
list1.sort();
list2.sort();
std::cout << "list1:  " << list1 << "\n";
std::cout << "list2:  " << list2 << "\n";
list1.merge(list2);
list1.unique();
std::cout << "merged: " << list1 << "\n";
like image 57
Humam Helfawi Avatar answered Dec 28 '22 23:12

Humam Helfawi