×

C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap

C++ STL MISC.

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

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.