Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::forward_list: a singly linked node container

std::forward_list stores a one-way chain and offers constant-time operations after a known predecessor.

Version: C++23

Syntax

template<class T, class Allocator = std::allocator<T>>
class std::forward_list;

// Selected operations:
iterator before_begin() noexcept;
void push_front(const T& value);
iterator insert_after(const_iterator position, const T& value);
iterator erase_after(const_iterator position);

std::forward_list<T, Allocator> from <forward_list> is a node-based sequence container with forward iterators. It provides no random access, operator[], back(), push_back(), or even size(). Reaching an element requires walking from begin(), so locating a position is linear.

The example constructs 2 3, pushes 1 at the front, and then inserts 9 after the first element; iteration prints 1 9 2 3. before_begin() is a special non-dereferenceable iterator preceding the first node, allowing insert_after, emplace_after, and erase_after to change the front as well.

Insertion or erasure of one element after a known predecessor is constant-time, as is relinking known chain endpoints; count and range forms scale with the number of elements constructed, erased, or transferred, and finding the predecessor can be linear. Insertion does not invalidate iterators or references to existing elements; erasure invalidates only those referring to erased elements. Neither before_begin() nor end() may be dereferenced, and erase_after(pos) requires an existing successor. Node-transfer operations such as splice_after require compatible allocators as stated by their preconditions.

Examples

#include <forward_list>
#include <iostream>

int main() {
    std::forward_list<int> values{2, 3};
    values.push_front(1);
    values.insert_after(values.begin(), 9);

    bool first = true;
    for (int value : values) {
        if (!first) std::cout << ' ';
        std::cout << value;
        first = false;
    }
    std::cout << '\n';
}

Result

1 9 2 3

std::forward_list → 1 9 2 3

Sources