Open In App

forward_list cbegin() in C++ STL

The forward_list::cbegin() is a function in C++ STL which returns a constant iterator pointing to the first element of the forward_list. Syntax:

forward_list_name.cbegin()

Parameters: This function does not accept any parameter. 

Return Value: This function returns an iterator that points to the const content. Since the iterator is not constant it can be increased or decreased or modified but as it cannot be used to modify its content even if the forward list is not constant. If the forward list is empty, the iterator returned by the function will not be dereferenced. The following programs illustrate the use of the function: 

Program 1: 




// CPP program to illustrate
// forward_list::cbegin();
 
#include <forward_list>
#include <iostream>
using namespace std;
 
int main()
{
    forward_list<int> sample = { 45, 87, 6 };
 
    // Get the first element by
    // dereferencing the iterator
    // returned by sample.cbegin()
    cout << "1st element of sample: ";
    cout << *sample.cbegin();
}

Output:
1st element of sample: 45

Time Complexity: O(1)

Auxiliary Space: O(1)

Program 2: 




#include <forward_list>
#include <iostream>
using namespace std;
 
int main()
{
    forward_list<int> sample = { 7, 4, 9, 15 };
 
    // Display the elements
 
    cout << "sample: ";
    for (auto it = sample.cbegin(); it != sample.cend(); it++)
        cout << *it << " ";
}

Output:
sample: 7 4 9 15

Time Complexity: O(1)

Auxiliary Space: O(1)


Article Tags :
C++