How do I merge and splice sequences with std::forward_list?

The std::forward_list container in C++ provides a lightweight alternative to std::list for singly-linked sequences. Merging and splicing are two useful operations that allow you to combine or reposition elements effectively.

Merging Sequences

To merge two std::forward_list sequences, you can use the merge member function. This function requires both lists to be sorted.

Splicing Sequences

The splice_after function allows you to move elements from one std::forward_list to another efficiently.

Example:

#include <forward_list> #include <iostream> int main() { std::forward_list<int> list1 = {1, 3, 5}; std::forward_list<int> list2 = {2, 4, 6}; // Merging sorted lists list1.sort(); list2.sort(); list1.merge(list2); // Output merged list std::cout << "Merged list: "; for (const auto &val : list1) { std::cout << val << " "; } std::cout << std::endl; // Splicing elements from list1 to list2 std::forward_list<int> list3 = {7, 9}; list2.splice_after(list2.before_begin(), list1, list1.before_begin(), list1.end()); // Output spliced list std::cout << "Spliced list2: "; for (const auto &val : list2) { std::cout << val << " "; } std::cout << std::endl; return 0; }

C++ std::forward_list merging sequences splicing sequences list manipulation