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


The C++ forward_list::begin function is used to return the 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 iterator pointing to the same element of the forward_list.

C++ begin end

Syntax

iterator begin() noexcept;
const_iterator begin() const noexcept;

Parameters

No parameter is required.

Return Value

An iterator to 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::begin function is used to return the iterator pointing to the first element of the forward_list called f_list.

#include <iostream>
#include <forward_list>
using namespace std;
 
int main (){
  forward_list<string> f_list{"Alpha","Coding","Skills"};
  forward_list<string>::iterator it;

  it = f_list.begin();
  cout<<*it<<" ";
  it++;
  cout<<*it<<" ";
  it++;
  cout<<*it<<" ";
  return 0;
}

The output of the above code will be:

Alpha Coding Skills

Example:

Lets see another example where the forward_list called f_list contains integer values and forward_list::begin function is used with forward_list::end 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> f_list{10, 20, 30, 40, 50};
  forward_list<int>::iterator it;

  for(it = f_list.begin(); it != f_list.end(); ++it)
    cout<<*it<<" ";

  return 0;
}

The output of the above code will be:

10 20 30 40 50 

❮ C++ - Forward List