Reversed Range-based for loop in C++ with Examples
Last Updated :
08 Jul, 2020
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
#include <bits/stdc++.h>
#include <boost/range/adaptor/reversed.hpp>
using namespace std;
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 };
for ( auto x : boost::adaptors::reverse(s))
cout << x << " " ;
cout << endl;
for ( auto x : boost::adaptors::reverse(y))
cout << x << " " ;
cout << endl;
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
Share your thoughts in the comments
Please Login to comment...