Open In App

Reversed Range-based for loop in C++ with Examples

Last Updated : 08 Jul, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

Range-based for loops is an upgraded version of for loops. It is quite similar to for loops which is use in Python. Range-based for loop in C++ is added since C++ 11.

We can reverse the process of iterating the loop by using boost::adaptors::reverse() function which is included in boost library Header.

Header File:

#include <boost/range/adaptor/reversed.hpp> 

Syntax:

for (auto i : boost::adaptors::reverse(x))

Parameters:

  • range_declaration: a declaration used to iterate over the elements in a container. Often uses the auto specifier for automatic type deduction.
  • range_expression: An expression that represents a suitable sequence or a braced-init-list.
  • loop_statement: An statement, typically a compound statement, which is the body of the loop.

Below is the program to illustrate reverse range based loop in C++:

CPP14




// C++ program for reverse
// range-based for loop
#include <bits/stdc++.h>
  
// For reversing range based loop
#include <boost/range/adaptor/reversed.hpp>
using namespace std;
  
// Driver Code
int main()
{
    string s = "geeksforgeeks";
  
    int y[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
  
    vector<int> v1{ 1, 2, 3, 4, 5, 6, 7, 8 };
  
    // Reverse range-based for loop
    // to reverse string
    for (auto x : boost::adaptors::reverse(s))
        cout << x << " ";
    cout << endl;
  
    // Reverse range-based for loop
    // to reverse array
    for (auto x : boost::adaptors::reverse(y))
        cout << x << " ";
    cout << endl;
  
    // Reverse range-based for loop
    // to reverse vector
    for (auto x : boost::adaptors::reverse(v1))
        cout << x << " ";
    cout << endl;
  
    return 0;
}


Output:

s k e e g r o f s k e e g 
8 7 6 5 4 3 2 1 
8 7 6 5 4 3 2 1

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads