问题
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