Skip to content
Related Articles

Related Articles

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

Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 13 Jun, 2022
Improve Article
Save Article
  • 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: 

CPP




// C++ program to illustrate the
// cbegin() function
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    // declaration of list
    list<int> lis = { 5, 6, 7, 8, 9 };
 
    // Prints the first element
    cout << "The first element is: " << *lis.cbegin();
 
    // printing list elements
    cout << "\nList: ";
 
    for (auto it = lis.cbegin(); it != lis.end(); ++it)
        cout << *it << " ";
 
    return 0;
}

Output: 

The first element is: 5
List: 5 6 7 8 9

 

Time Complexity: O(1)

Auxiliary Space: O(1)

  • 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 accepts any parameter.
Return value: It returns a constant random access iterator which points to the end of the list.
Below program illustrates the function:

CPP




// C++ program to illustrate the
// cend() function
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
 
    // declaration of list
    list<int> lis = { 10, 20, 30, 40, 50 };
 
    // printing list elements
    cout << "List: " << endl;
 
    for (auto it = lis.cbegin(); it != lis.cend(); ++it)
        cout << *it << " ";
 
    return 0;
}

Output: 

List: 
10 20 30 40 50

 

Time Complexity: O(1)

Auxiliary Space: O(1)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!