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

In C++, the `std::list` class provides several member functions that allow you to manipulate sequences easily. Merging two lists and splicing elements from one list to another is straightforward with these member functions.

Merging Two Lists

The `merge()` function can be used to merge two sorted lists into one. It merges the elements of the second list into the first list in sorted order.

Splicing Elements

The `splice()` function allows you to transfer elements from one list to another without invoking the copy or move constructors, offering efficiency advantages.

Example of Merging and Splicing with std::list


#include <iostream>
#include <list>

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

    // Merging list2 into list1
    list1.merge(list2);
    
    std::cout << "Merged list: ";
    for (const int &num : list1) {
        std::cout << num << ' ';
    }
    std::cout << std::endl;

    // Splicing elements
    std::list<int> splicedList;
    splicedList.splice(splicedList.end(), list1, ++list1.begin(), list1.end()); // Splice all but the first element

    std::cout << "Spliced list: ";
    for (const int &num : splicedList) {
        std::cout << num << ' ';
    }

    return 0;
}
    

C++ std::list merge splice list manipulation sequences