Skip to content

Instantly share code, notes, and snippets.

@ppwwyyxx
Last active April 20, 2020 21:32
Show Gist options
  • Save ppwwyyxx/203e386a26aabc63931c to your computer and use it in GitHub Desktop.
Save ppwwyyxx/203e386a26aabc63931c to your computer and use it in GitHub Desktop.
C++11 Reverse Iterator Used in Ranged For Loop
//File: reverse_iterator.cpp
//Date: Thu Jul 17 09:54:05 2014 -0700
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <cstdio>
#include <limits>
using namespace std;
#define REP(x, y) for (auto x = decltype(y){0}; x < (y); x ++)
#define REPL(x, y, z) for (auto x = decltype(z){y}; x < (z); x ++)
#define REPD(x, y, z) for (auto x = decltype(z){y}; x >= (z); x --)
#define P(a) std::cout << (a) << std::endl
#define PP(a) std::cout << #a << ": " << (a) << std::endl
#define PA(arr) \
do { \
std::cout << #arr << ": "; \
std::copy(begin(arr), end(arr), std::ostream_iterator<std::remove_reference<decltype(arr)>::type::value_type>(std::cout, " ")); \
std::cout << std::endl; \
} while (0)
template <typename T>
class ReverseIterator {
public:
typedef typename T::const_reverse_iterator Titer;
ReverseIterator(const T& t): t_(t) {}
Titer begin() const { return t_.rbegin();}
Titer end() const {return t_.rend();}
private:
const T& t_;
};
template <typename T>
ReverseIterator<T> make_riter(const T& t) {
return ReverseIterator<T>(t);
}
int main() {
vector<int> a {1, 2, 3, 4, 5};
for (auto & k : make_riter(a))
PP(k);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment