Merging Sorted Lists in std::forward_list
How can I merge two sorted forward_list objects into one sorted list?
The merge() member function in std::forward_list merges two sorted lists into one. The lists must be sorted before calling merge().
#include <forward_list>
#include <iostream>
int main() {
std::forward_list<int> list1{1, 3, 5};
std::forward_list<int> list2{2, 4, 6};
list1.merge(list2);
for (int i : list1) {
std::cout << i << ' ';
}
std::cout << '\n';
for (int i : list2) {
std::cout << i << ' ';
}
}1 2 3 4 5 6After merging, the elements of list2 are transferred to list1, leaving list2 empty.
You can also provide a custom comparison function:
#include <forward_list>
#include <iostream>
bool descendingOrder(int first, int second) {
return first > second;
}
int main() {
std::forward_list<int> list1 {5, 3, 1};
std::forward_list<int> list2 {6, 4, 2};
list1.merge(list2, descendingOrder);
for (int i : list1) {
std::cout << i << ' ';
}
}6 5 4 3 2 1This merges the lists in descending order according to the descendingOrder function.
Linked Lists using std::forward_list
This lesson provides an in-depth exploration of std::forward_list, covering creation, management, and advanced list operations