C++ <list> - begin() Function
The C++ list::begin function returns the iterator pointing to the first element of the list. Please note that, Unlike the list::front function, which returns a direct reference to the first element, it returns the iterator pointing to the same element of the list.
Syntax
iterator begin(); const_iterator begin() const;
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 list::begin function returns the iterator pointing to the first element of the list called MyList.
#include <iostream> #include <list> using namespace std; int main (){ list<string> MyList{"Alpha","Coding","Skills"}; list<string>::iterator it; it = MyList.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 list called MyList contains integer values and list::begin function is used with list::end function to specify a range including all elements of the list container.
#include <iostream> #include <list> using namespace std; int main (){ list<int> MyList{10, 20, 30, 40, 50}; list<int>::iterator it; for(it = MyList.begin(); it != MyList.end(); ++it) cout<<*it<<" "; return 0; }
The output of the above code will be:
10 20 30 40 50
❮ C++ <list> Library