C++ Reverse Range-based for loop
Thursday, October 28, 2021
To make C++11 range-based for loop interate backwards, we can use this adaptor:
#include<iterator>
#include <iostream>
#include <vector>
namespace detail {
template <typename T>
struct rev_wrapper_r {
T& _iterable;
auto begin() const {return std::rbegin(_iterable);}
auto end() const {return std::rend(_iterable);}
};
template <typename T>
struct rev_wrapper_v {
T _iterable;
auto begin() const {return std::rbegin(_iterable);}
auto end() const {return std::rend(_iterable);}
};
}
template <typename T>
detail:: rev_wrapper_r<T> reverse (T& iterable) { return { iterable }; }
template <typename T>
detail:: rev_wrapper_v<T> reverse (T&& iterable) { return { iterable }; }
int main(){
std::vector<int> v{ 1, 2, 3 };
for (const auto& i : reverse(v)) {
std::cout << i << std::endl;
}
for (const auto& i : reverse(std::vector<int>{1,2,3,4,5})) {
std::cout << i << std::endl;
}
return 0;
}
Live Demo:
https://wandbox.org/permlink/cUS4hrrHDwyacr7X