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 6

After 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 1

This 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

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Iterator Invalidation in std::forward_list
When do iterators become invalidated in a std::forward_list?
Using splice_after() in std::forward_list
How can I transfer elements from one forward_list to another using splice_after()?
Removing Consecutive Duplicates in std::forward_list
How can I remove consecutive duplicate elements from a forward_list?
Using Lambda Expressions with remove_if() in std::forward_list
How can I use a lambda expression as the predicate for remove_if() in a forward_list?
Reversing Elements in std::forward_list
How can I reverse the order of elements in a forward_list?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant