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
Problem statement
Given a list and we have to iterate its all elements and print in new line in C++.
Here is an example with sample input and output:
Input: list num{10, 20, 30, 40, 50}
Output:
List elements are:
10
20
30
40
50
Iterating a list
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<int>::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();
C++ program to iterate a list
#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