English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
C ++ The List merge() function merges two sorted lists in ascending order. It merges the y list into the given list container, removing all elements from y.
If no comparator is passed in the parameters, two sorted lists will be merged into one list.
If a comparator is passed in the parameters, the list will be merged according to its internal comparison.
two lists list1and list2.Syntax is:
list1.merge(list2); list1.merge(list2,compare);
list2: To be merged with list1The merged list.
compare: This is a comparator function object used to compare the value of the first parameter with the value of the second parameter. If the value of the first parameter is less than the value of the second parameter, it returns true; otherwise, it returns false.
It does not return any value.
Let's look at a simple example
#include <iostream> #include<list> using namespace std; int main() { list<int> li={1,2,3,4}); list<int> li1={5,6,7,8}); li.merge(li1); for(list<int>::iterator itr = li.begin(); itr != li.end();++itr){ std::cout << *itr << " " << std::endl; } return 0; }
Output:
1 2 3 4 5 6 7 8
In this example, the merge() function will merge the list li with the list li1Merge into a list.
Let's look at a simple example when the comparator is passed as a parameter
#include <iostream> #include<list> using namespace std; bool comparison(int first, int second) { bool a; a = first < second; return (a); } int main() { list<int> li={9,10,11}); list<int> li1={5,6,7,15}); li.merge(li1,comparison); for(list<int>::iterator itr = li.begin(); itr != li.end();++itr){ std::cout << *itr << " " << std::endl; } return 0; }
Output:
5 6 7 9 10 11 15
In this example, the merge() function merges the lists based on the internal comparison.