C++ <array> - cbegin() Function
The C++ array::cbegin function returns the constant iterator (const_iterator) pointing to the first element of the array. Please note that, Unlike the array::front function, which returns a direct reference to the first element, it returns the const_iterator pointing to the same element of the array.
Note: A const_iterator is an iterator that points to constant value. The difference between iterator and const_iterator is that the const_iterator cannot be used to modify the content it points to, even if the array element is not itself constant.
Syntax
const_iterator cbegin() const noexcept;
Parameters
No parameter is required.
Return Value
A const_iterator to the beginning of the sequence container.
Time Complexity
Constant i.e, Θ(1)
Example:
In the example below, the array::cbegin function returns the const_iterator pointing to the first element of the array called MyArray.
#include <iostream> #include <array> using namespace std; int main (){ array<string, 3> MyArray{"Alpha","Coding","Skills"}; array<string, 3>::const_iterator cit; cit = MyArray.cbegin(); cout<<*cit<<" "; cit++; cout<<*cit<<" "; cit++; cout<<*cit<<" "; return 0; }
The output of the above code will be:
Alpha Coding Skills
Example:
Lets see another example where the array called MyArray contains integer values and array::cbegin function is used with array::cend function to specify a range including all elements of the array container.
#include <iostream> #include <array> using namespace std; int main (){ array<int, 5> MyArray{10, 20, 30, 40, 50}; array<int, 5>::const_iterator cit; for(cit = MyArray.cbegin(); cit != MyArray.cend(); ++cit) cout<<*cit<<" "; return 0; }
The output of the above code will be:
10 20 30 40 50
❮ C++ <array> Library