Using splice_after() in std::forward_list

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

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.

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?
Removing Consecutive Duplicates in std::forward_list
How can I remove consecutive duplicate elements from a forward_list?
Merging Sorted Lists in std::forward_list
How can I merge two sorted forward_list objects into one sorted 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