Home
Aptitude
Categories


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 July 02, 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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.