Skip to content
Related Articles

Related Articles

Improve Article

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

  • Difficulty Level : Basic
  • Last Updated : 19 Jul, 2018
  1. 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>
    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
    
  2. 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>
    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
    
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.



My Personal Notes arrow_drop_up
Recommended Articles
Page :