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

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> 


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


  • 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++:






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



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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at to report any issue with the above content.