C++ Standard Library C++ STL Library

C++ <forward_list> - cbegin() Function



The C++ forward_list::cbegin function returns the constant iterator (const_iterator) pointing to the first element of the forward_list. Please note that, Unlike the forward_list::front function, which returns a direct reference to the first element, it returns the const_iterator pointing to the same element of the forward_list.

C++ cbegin cend

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 cbegin() const noexcept;

Parameters

No parameter is required.

Return Value

A const_iterator to the beginning of the sequence container.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the forward_list::cbegin function returns the const_iterator pointing to the first element of the forward_list called flist.

#include <iostream>
#include <forward_list>
using namespace std;
 
int main (){
  forward_list<string> flist{"Alpha","Coding","Skills"};
  forward_list<string>::const_iterator cit;

  cit = flist.cbegin();
  cout<<*cit<<" ";
  cit++;
  cout<<*cit<<" ";
  cit++;
  cout<<*cit<<" ";
  return 0;
}

The output of the above code will be:

Alpha Coding Skills

Example:

Lets see another example where the forward_list called flist contains integer values and forward_list::cbegin function is used with forward_list::cend function to specify a range including all elements of the forward_list 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;

  for(cit = flist.cbegin(); cit != flist.cend(); ++cit)
    cout<<*cit<<" ";

  return 0;
}

The output of the above code will be:

10 20 30 40 50 

❮ C++ <forward_list> Library