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.
To merge two std::forward_list
sequences, you can use the merge
member function. This function requires both lists to be sorted.
The splice_after
function allows you to move elements from one std::forward_list
to another efficiently.
#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;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?