C++ <array> - begin() Function
The C++ array::begin function returns the 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 iterator pointing to the same element of the array.
Syntax
iterator begin() noexcept; const_iterator begin() const noexcept;
Parameters
No parameter is required.
Return Value
An iterator to the beginning of the sequence container. If the sequence object is constant qualified, the function returns a const_iterator, else returns an iterator.
Time Complexity
Constant i.e, Θ(1).
Example:
In the example below, the array::begin function returns the 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>::iterator it; it = MyArray.begin(); cout<<*it<<" "; it++; cout<<*it<<" "; it++; cout<<*it<<" "; 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::begin function is used with array::end 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>::iterator it; for(it = MyArray.begin(); it != MyArray.end(); ++it) cout<<*it<<" "; return 0; }
The output of the above code will be:
10 20 30 40 50
❮ C++ <array> Library