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!

Load comments ↻





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