Iterating a vector in reverse order with a range-for loop? [duplicate]

只愿长相守 提交于 2021-02-10 06:58:02

问题


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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/61182699/iterating-a-vector-in-reverse-order-with-a-range-for-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!