C++ Standard Library C++ STL Library

C++ <forward_list> - before_begin() Function



The C++ forward_list::before_begin function returns 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 example below, the forward_list::before_begin function returns the iterator pointing to the position before the first element of the forward_list called flist. It is used to insert first element in the container.

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

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

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

  return 0;
}

The output of the above code will be:

flist contains: -10 10 20 30 40 50 

❮ C++ <forward_list> Library

5