Linked Lists using std::forward_list

Merging Sorted Lists in std::forward_list

How can I merge two sorted forward_list objects into one sorted list?

Abstract art representing computer programming

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.

Answers to questions are automatically generated and may not have been reviewed.

Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved