×

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 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

Problem statement

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

Iterating a list in reverse order

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();

Here is an example with sample input and output:

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

C++ program to iterate a list in reverse order

#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.