forward list::cend() in C++ STL

C++Server Side ProgrammingProgramming

Given is the task to show the working of forward_list::cend functions 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::cend() function is a part of the C++ standard template library. It is used to obtain the last element of the list.

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

Syntax

Forward_List_Name.cend();

Parameters

The function does not accept any parameter.

Return Value

The function returns a constant iterator that points at the last element of the forward_list.

Example

Input: forward_list<int> Lt={8, 9, 7};
cout<< *Lt.cend();
Output: 7

Explanation: Here we created a list with elements 8,9 and 7. Then we called the cend() function that points at the last element of the list. So when we print it, the output generated is 7, which is the last 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.
  • The 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() functions. 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 = { 9,55,6,100 };
   //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 −

9 55 6 100
raja
Published on 20-Jan-2020 10:04:55
Advertisements