list cbegin() and cend() function in C++ STL
- The list::cbegin() is a built-in function in C++ STL which returns a constant random access iterator which points to the beginning of the list. Hence the iterator obtained can be used to iterate container but cannot be used to modify the content of the object to which it is pointing even if the object itself is not constant.
Syntax:
list_name.cbegin()
Parameters: The function does not accept any parameters.
Return value: It returns a constant random access iterator which points to the beginning of the list.
Below programs illustrate the above function:
// C++ program to illustrate the// cbegin() function#include <bits/stdc++.h>usingnamespacestd;intmain(){// declaration of listlist<int> lis = { 5, 6, 7, 8, 9 };// Prints the first elementcout <<"The first element is: "<< *lis.cbegin();// printing list elementscout <<"\nList: ";for(autoit = lis.cbegin(); it != lis.end(); ++it)cout << *it <<" ";return0;}Output:The first element is: 5 List: 5 6 7 8 9
- The list::cend() is a built-in function in C++ STL which returns a constant random access iterator which points to the end of the list. Hence the iterator obtained can be used to iterate container but cannot be used to modify the content of the object to which it is pointing even if the object itself is not constant.
Syntax:
list_name.cend()
Parameters: The function does not acceps any parameter.
Return value: It returns a constant random access iterator which points to the end of the list.
Below program illustrates the function:
// C++ program to illustrate the// cend() function#include <bits/stdc++.h>usingnamespacestd;intmain(){// declaration of listlist<int> lis = { 10, 20, 30, 40, 50 };// printing list elementscout <<"List: "<< endl;for(autoit = lis.cbegin(); it != lis.cend(); ++it)cout << *it <<" ";return0;}Output:List: 10 20 30 40 50
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.


