Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::list — sequences and element transfer with splice

std::list is a sequence container with bidirectional iterators. Learn begin(), empty(), and splice(): transferring elements between lists while preserving their identity, including complexity and the conditions required for valid use.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <list>
std::list<T> values;
values.begin();
values.empty();
dst.splice(pos, src);
dst.splice(pos, src, it);
dst.splice(pos, src, first, last);

std::list<T> from <list> stores an ordered sequence and provides bidirectional iterators. Inserting or erasing one element at a known position costs O(1); finding that position may require traversing the list. There is no random access, operator[], or at().

std::list::begin() returns an iterator to the first element; for an empty list it equals end() and must not be dereferenced. For a const list it returns const_iterator. std::list::empty() tests whether the list contains no elements; it does not erase them. Both operations cost O(1).

std::list::splice transfers existing elements before pos, without copying or move-constructing their values. dst.splice(pos, src) transfers the entire list in O(1) and leaves src empty. dst.splice(pos, src, it) transfers one element in O(1). The first, last form transfers [first, last): O(1) within the same list, otherwise O(n) in the transferred range. Pointers, references, and iterators to these elements remain valid; those iterators now belong to the destination list.

pos must be a valid destination position, including end(). Both lists' allocators must compare equal; otherwise behavior is undefined. The whole-list form requires distinct objects. The single-element form requires a dereferenceable it from src; within the same list, positioning it at it or immediately after it changes nothing. The range form requires a valid range in src and pos outside that range.

The example demonstrates an emptied source and the preserved iterator saved. Entry scope: C++23; a repository compiler flag does not attest the production runtime. The cited site contains an evolving draft, not frozen C++23 wording; do not project its newer constexpr declarations onto C++23.

Examples

#include <iostream>
#include <list>

int main() {
    std::list<int> dst{30};
    std::list<int> src{10, 20};
    auto saved = src.begin();

    dst.splice(dst.begin(), src);

    std::cout << std::boolalpha;
    std::cout << "src.empty(): " << src.empty() << '\n';
    std::cout << "saved: " << *saved << '\n';
    std::cout << "dst:";
    for (int value : dst) {
        std::cout << ' ' << value;
    }
    std::cout << '\n';
}

Result

src.empty(): true
saved: 10
dst: 10 20 30

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources