Home »
C++ STL
Iterate a list (Example of list::begin() and list::end() functions) | C++ STL
In this article, we are going to learn how to iterate a list in C++ STL? Here, we will also learn about the list::begin() and list::end() functions – which are predefined functions of "list" header in C++ STL.
Submitted by IncludeHelp, on August 22, 2018
Given a list and we have to iterate its all elements and print in new line in C++.
Example:
Input: list num{10, 20, 30, 40, 50}
Output:
List elements are:
10
20
30
40
50
List iterator
To iterate a list in C++ STL, we need an iterator that should be initialized with the first element of the list and we need to check it till the end of the list.
List iterator declaration:
list::iterator it;
list::begin() and list::end() functions
The function list::begin() returns an iterator pointing to the first element i.e. returns reference to the first element and list::end() returns an iterate pointing to the last element.
Syntax:
list_name.begin();
list_name.end();
Program:
#include <iostream>
#include <list>
using namespace std;
int main() {
// declare a list
list<int>num {10, 20, 30, 40, 50};
//declare an interator
list<int>::iterator it;
//run loop using begin() end() functons
cout<< "List elements are: " <<endl;
for ( it=num.begin (); it!=num.end (); it++)
cout<< *it <<endl;
return 0;
}
Output
List elements are:
10
20
30
40
50