Skip to main content

std::forward_list before_begin()/cbefore_begin() method

// Non-const version
iterator begin() noexcept;

// Const version
const_iterator begin() const noexcept;
const_iterator cbegin() const noexcept;

Returns an iterator to the element before the first element of the container.

Undefined Behavior

This element acts as a placeholder, attempting to access it results in undefined behavior

.

The only usage cases are in functions insert_after(), emplace_after(), erase_after(), splice_after() and the increment operator: incrementing the before-begin iterator gives exactly the same iterator as obtained from begin/cbegin().

Parameters

(none)

Return value

Iterator to the element before the first element.

Complexity

Constant - O(1).

Difference between before_begin and cbefore_begin

For a const container c, before_begin and cbefore_begin are the same - c.before_begin() == c.cbefore_begin()

For non-const container of type c they return different iterators:

#include <forward_list>

int main()
{
std::forward_list<int> arr = {1, 2, 3, 4, 5};
auto it = arr.before_begin(); // Type: std::forward_list<int>::iterator
*std::next(it) = 5; // ✔ Ok
}

Example

important

This section requires improvement. You can help by editing this doc page.

This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.

std::forward_list before_begin()/cbefore_begin() method

// Non-const version
iterator begin() noexcept;

// Const version
const_iterator begin() const noexcept;
const_iterator cbegin() const noexcept;

Returns an iterator to the element before the first element of the container.

Undefined Behavior

This element acts as a placeholder, attempting to access it results in undefined behavior

.

The only usage cases are in functions insert_after(), emplace_after(), erase_after(), splice_after() and the increment operator: incrementing the before-begin iterator gives exactly the same iterator as obtained from begin/cbegin().

Parameters

(none)

Return value

Iterator to the element before the first element.

Complexity

Constant - O(1).

Difference between before_begin and cbefore_begin

For a const container c, before_begin and cbefore_begin are the same - c.before_begin() == c.cbefore_begin()

For non-const container of type c they return different iterators:

#include <forward_list>

int main()
{
std::forward_list<int> arr = {1, 2, 3, 4, 5};
auto it = arr.before_begin(); // Type: std::forward_list<int>::iterator
*std::next(it) = 5; // ✔ Ok
}

Example

important

This section requires improvement. You can help by editing this doc page.

This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.