forward_list cbegin() in C++ STL

C++Server Side ProgrammingProgramming

Given is the task to show the working of forward_list::cbegin() function in C++.

A forward_list only keeps linkage with the next element unlike normal list that keeps linkage with the next as well as the preceding elements, which helps iterations in both directions. But forward_list can only iterate in the forward direction.

The forward_list::cbegin() function is a part of the C++ standard template library. It is used to obtain the very first element of the list.

<forward_list> header file should be included to call the function.

Syntax

Forward_List_Name.cbegin();

Parameters

The function does not accept any parameter.

Return Value

The function returns a constant iterator that point at the first element of the forward_list.

Example

Input: 11, 4, 99
Output: 11

Explanation

Here we created a forward list with elements 11,4 and 99. Then we called the cbegin() function that points at the first element of the list.

So when we print it, the output generated is 11, which is the first element of the list.

Approach used in the below program as follows

  • First create a forward_list, let us say “Lt” of type int and assign it some values.
  • Then start a For loop for printing the list.
  • Then create an object “itr” of type auto inside the for loop for receiving the return values of cend() and cbegin() function. Initialize “itr” by giving it the first element of the list using the cbegin() function.
  • Then specify the terminating condition of the for loop by writing “itr” not equal to the last element of the list using the cend() function.
  • Print *itr.

Algorithm

Start
Step 1->In function main()
   Initialize forward_list<int> Lt={}
   Loop For auto itr = Lt.cbegin() and itr != Lt.cend() and itr++
   Print *itr
   End
Stop

Example

#include<iostream>
#include<list>
using namespace std;
int main() {
   forward_list<int> Lt = { 67,88,99,10 };
   //Printing the elements of the list
   cout <<"The elements of the list are : " <<"\n";
   for (auto itr = Lt.cbegin(); itr != Lt.cend(); itr++)
   cout << *itr << " ";
   return 0;
}

Output

If we run the above code it will generate the following output −

67 88 99 10
raja
Published on 20-Jan-2020 14:32:37
Advertisements