Home
Aptitude
Categories


Home » C++ STL

Iterate a list in reverse order (Example of list::rbegin() and list::rend() functions) | C++ STL



In this article, we are going to learn how to iterate a list in reverse order in C++ STL? Here, we will also learn about the list::rbegin() and list::rend() functions – which are predefined functions of list header in C++ STL. Submitted by IncludeHelp, on August 24, 2018

Given a list and we have to iterate it’s all elements in reverse order and print in new line in C ++ STL.

List reverse_iterator

To iterate a list in reverse order in C++ STL, we need an reverse_iterator that should be initialized with the last element of the list, as a reverse order and we need to check it till the end of the list.

List reverse iterator declaration:

 list<int>::reverse_iterator revit;

list::rbegin() and list::rend() functions

The function list::rbegin() returns a reverse iterator pointing to the first element from the end or we can say as the reverse beginning.

Syntax:

 list_name.rbegin();

The function list::rend() returns a reverse iterator pointing to the last element from the end or we can say as the reverse ending.

Syntax:

 list_name.rend();

Example:

    Input: 
    list num{10, 20, 30, 40, 50}
    
    Output:
    List elements are:
    50
    40
    30
    20
    10

Program:

#include <iostream>
#include <list>

using namespace std;

int main() {
	// declare a list
	list<int>num {10, 20, 30, 40, 50};
	
	//declare an iterator
	list<int>:: reverse_iterator revit;

	//run loop using begin () end () functons
	cout<< "List elements are: " <<endl;
	for( revit=num.rbegin(); revit!=num.rend(); revit++ )
		cout<< *revit<<endl;

	return 0;
}

Output

    List elements are: 
    50
    40
    30
    20
    10





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.