Linked Lists using std::forward_list

Using splice_after() in std::forward_list

How can I transfer elements from one forward_list to another using splice_after()?

Abstract art representing computer programming

The splice_after() member function in std::forward_list allows you to transfer elements from one list to another in constant time. It comes in three forms:

Splicing a single element:

#include <forward_list>
#include <iostream>

int main() {
  std::forward_list<int> list1{1, 2, 3};
  std::forward_list<int> list2{4, 5, 6};

  auto it = list1.begin();
  list1.splice_after(it, list2, list2.begin());  

  std::cout << "List 1: ";
  for (auto i : list1) {
    std::cout << i << ", ";
  }

  std::cout << "\nList 2: ";
  for (auto i : list2) {
    std::cout << i << ", ";
  }
}
List 1: 1, 5, 2, 3,
List 2: 4, 6,

Splicing a range of elements:

#include <forward_list>
#include <iostream>

int main() {
  std::forward_list<int> list1{1, 2, 3};
  std::forward_list<int> list2{4, 5, 6, 7};

  auto it = list1.begin();
  list1.splice_after(it, list2, list2.begin(),
                     std::next(list2.begin(), 2));  

  std::cout << "List 1: ";
  for (auto i : list1) {
    std::cout << i << ", ";
  }

  std::cout << "\nList 2: ";
  for (auto i : list2) {
    std::cout << i << ", ";
  }
}
List 1: 1, 5, 2, 3,
List 2: 4, 6, 7,

Splicing an entire list:

#include <forward_list>
#include <iostream>

int main() {
  std::forward_list<int> list1{1, 2};
  std::forward_list<int> list2{3, 4, 5};

  list1.splice_after(list1.before_begin(),
                     list2);  

  std::cout << "List 1: ";
  for (auto i : list1) {
    std::cout << i << ", ";
  }

  std::cout << "\nList 2: ";
  for (auto i : list2) {
    std::cout << i << ", ";
  }
}
List 1: 3, 4, 5, 1, 2,
List 2:

Note that the elements are inserted after the given position. The source list is left empty if the entire list is spliced.

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