list cbegin() and cend() functions in C++ STL

C++Server Side ProgrammingProgramming

Given is the task to show the working of list::cbegin() and list::cend functions in C++.

The list::cbegin() and list::cend() functions are a part of the C++ standard template library.

<list> header file should be included to call these functions.

  • list::cbegin()

    This function returns the constant iterator which points to the beginning element of the list. It can be used to traverse the list but it cannot change the values in the list which means cbegin() function can be used for iteration only.

Syntax

List_Name.cbegin();

Parameters

The function does not accept any parameter.

Return Value

The function returns a constant iterator that point at the beginning element of the list.

  • list::cend()

    This function returns the constant iterator which points to the end element of the list. It can be used for Backtracking the list but it cannot change the values in the list which means cend() function can be used for iteration only.

Syntax

List_Name.cend();

Parameters

The function does not accept any parameter.

Return Value

The function returns a constant iterator that point at the last element of the list.

Example

Input: list<int> Lt={4,8,9}
Output: 4

Explanation − Here we created a list with elements 4,8,9. Then we called the cbegin() function that points at the first element of the list.

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

Approach used in the below program as follows −

  • First create a list, let us say “Ld” of type int and assign it some values.
  • Then start a loop for printing the elements in the list.
  • After that create an object “itr” of type auto inside the for loop for receiving the return values of cend() and cbegin() function. Initialize “itr” by assigning 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 the value of *itr.

Algorithm

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

Example

 Live Demo

#include<iostream>
#include<list>
using namespace std;
int main() {
   list<int> Lt = { 4,1,7,9,6 };
   //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 −

4 1 7 9 6
raja
Published on 20-Jan-2020 07:19:07
Advertisements