C++ <list> merge function
mergeis used in list forMerge two sorted linked listsis a highly efficient operation unique to linked lists.
mergeis a member function of the container class, used to merge another sorted linked list into the current linked list.
After merging, the elements of the two linked lists are combined in order, and the current linked list becomes sorted.
Word Definitions: mergemeans "merge", i.e., merging two sorted linked lists.
Basic syntax and parameters
Syntax format
void merge(list& other); void merge(list& other, Compare comp);
Parameter description
- Parameter:
other- The linked list to be merged (will be cleared)
Function description
- Return Value:
void(No return value). - Effect: Merge two sorted linked lists,
otherbecomes empty.
Example
Example 1: Merge two sorted linked lists
Example
#include <iostream>
#include <list>
int main() {
std::list<int> list1 = {1, 3, 5, 7, 9};
std::list<int> list2 = {2, 4, 6, 8, 10};
std::cout << "list1: ";
for(int n : list1) std::cout << n << " ";
std::cout << std::endl;
std::cout << "list2: ";
for(int n : list2) std::cout << n << " ";
std::cout << std::endl;
// merge
list1.merge(list2);
std::cout << "After merge, list1: ";
for(int n : list1) std::cout << n << " ";
std::cout << std::endl;
std::cout << "After merge, list2 size: " << list2.size() << std::endl;
return 0;
}
#include <list>
int main() {
std::list<int> list1 = {1, 3, 5, 7, 9};
std::list<int> list2 = {2, 4, 6, 8, 10};
std::cout << "list1: ";
for(int n : list1) std::cout << n << " ";
std::cout << std::endl;
std::cout << "list2: ";
for(int n : list2) std::cout << n << " ";
std::cout << std::endl;
// merge
list1.merge(list2);
std::cout << "After merge, list1: ";
for(int n : list1) std::cout << n << " ";
std::cout << std::endl;
std::cout << "After merge, list2 size: " << list2.size() << std::endl;
return 0;
}
Expected run result:
list1: 1 3 5 7 9 list2: 2 4 6 8 10 合并后 list1: 1 2 3 4 5 6 7 8 9 10 合并后 list2 大小: 0
Example 2: After merging, list2 is cleared.
Example
#include <iostream>
#include <list>
int main() {
std::list<int> a = {1, 5, 6};
std::list<int> b = {2, 3, 4, 7};
a.merge(b);
std::cout << "After merge: ";
for(int n : a) std::cout << n << " ";
std::cout << std::endl;
std::cout << "b is empty: " << (b.empty() ? Yes : No) << std::endl;
return 0;
}
#include <list>
int main() {
std::list<int> a = {1, 5, 6};
std::list<int> b = {2, 3, 4, 7};
a.merge(b);
std::cout << "After merge: ";
for(int n : a) std::cout << n << " ";
std::cout << std::endl;
std::cout << "b is empty: " << (b.empty() ? Yes : No) << std::endl;
return 0;
}
Expected run result:
After merging: 1 2 3 4 5 6 7 b 是否为空: 是
other extensions