2

I want to iterate a vector in reverse order , i know that i can do it easily by below code

#include<bits/stdc++.h>
using namespace std;
int main()
{
    vector<int> v(10);
    for(auto it=v.rbegin();it!=v.rend();it++)
        cout<<*it<<"";
}

For iterating in forward we can simply do by below code.

for(auto it:v)
  cout<<it<<" ";

Now task is ...

Is it possible to do reverse iterate similar to for(auto it:v) cout<<it<<" ". If YES then How?

einpoklum
  • 118,144
  • 57
  • 340
  • 684
JitendraJat
  • 53
  • 1
  • 8

2 Answers2

7

If you can use C++20, you can use the ranges library and thus std::ranges::reverse_view:

vector<int> v(10);
std::ranges::reverse_view vReversed{v};

for(auto it : vReversed)
    cout<<it<<" ";
Lukas-T
  • 11,133
  • 3
  • 20
  • 30
0

Or you can write one on your own. Something like

template<class Source>
struct Reverse {
     Reverse(Source &&s): s(std::forward<Source>(s)) {}
     constexpr decltype(auto) begin() const { return std::rbegin(s); }
     constexpr decltype(auto end() const { return std::rend(s); }
private:
     S &&s;
};
bipll
  • 11,747
  • 1
  • 18
  • 32
  • Are you aware that `s` _is not_ a forwarding reference? You cannot construct `Reverese` with an lvalue vector ([live demo](https://godbolt.org/z/yAppFg)). Also, there are typos in your code. Please, try to compile and use it first before posting here. – Daniel Langr Apr 13 '20 at 06:55
  • @DanielLangr ... or simply admit that "something like" is not synonymous with "production-ready". – bipll Apr 13 '20 at 07:10