Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


The C++ forward_list::before_begin function is used to return the iterator pointing to the position before the first element of the forward_list. It is the theoretical element that does not point to any element, and hence could not be dereferenced. It acts as a placeholder and used as an argument for member functions emplace_after, insert_after, erase_after or splice_after. Increasing the before_begin iterator gives exactly the same iterator as obtained from begin/ cbegin.

Syntax

iterator before_begin() noexcept;
const_iterator before_begin() const noexcept;

Parameters

No parameter is required.

Return Value

An iterator to the position before the beginning of the sequence container. If the sequence object is constant qualified, the function returns a const_iterator, else returns an iterator.

Time Complexity

Constant i.e, Θ(1).

Example:

In the below example, the forward_list::before_begin function is used to return the iterator pointing to the position before the first element of the forward_list called f_list. It is used to insert first element in the container.

#include <iostream>
#include <forward_list>
using namespace std;
 
int main (){
  forward_list<int> f_list{10, 20, 30, 40, 50};
  forward_list<int>::iterator it;

  it = f_list.before_begin();
  f_list.insert_after(it, -10);

  cout<<"f_list contains: ";
  for(int&x : f_list)
    cout<<x<<" ";

  return 0;
}

The output of the above code will be:

f_list contains: -10 10 20 30 40 50 

❮ C++ - Forward List