C++ Standard Library C++ STL Library

C++ <forward_list> - cbefore_begin() Function



The C++ forward_list::cbefore_begin function returns the const_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.

Note: A const_iterator is an iterator that points to constant value. The difference between iterator and const_iterator is that the const_iterator cannot be used to modify the content it points to, even if the forward_list element is not itself constant.

Syntax

const_iterator cbefore_begin() const noexcept;

Parameters

No parameter is required.

Return Value

A const_iterator to the position before the beginning of the sequence container.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the forward_list::cbefore_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>::const_iterator cit;

  cit = flist.cbefore_begin();
  flist.insert_after(cit, -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