fork(2) download
  1. #include <iostream>
  2. #include <vector>
  3. #include <iterator>
  4.  
  5. template<typename It>
  6. class Range
  7. {
  8. It b, e;
  9. public:
  10. Range(It b, It e) : b(b), e(e) {}
  11. It begin() const { return b; }
  12. It end() const { return e; }
  13. };
  14.  
  15. template<typename ORange, typename OIt = decltype(std::begin(std::declval<ORange>())), typename It = std::reverse_iterator<OIt>>
  16. Range<It> reverse(ORange && originalRange) {
  17. return Range<It>(It(std::end(originalRange)), It(std::begin(originalRange)));
  18. }
  19.  
  20. int main() {
  21. std::vector<int> c = { 1, 2, 3, 4 };
  22. for (auto i : reverse(c)) {
  23. std::cout << i << ' ';
  24. }
  25. std::cout << std::endl;
  26.  
  27. // Also works with const containers
  28. const std::vector<int> cc = { 1, 2, 3, 4 };
  29. for (auto i : reverse(cc)) {
  30. std::cout << i << ' ';
  31. }
  32. std::cout << std::endl;
  33.  
  34. // Also works with raw arrays thanks to non-members std::begin/end
  35. int arr[] = { 1, 2, 3, 4 };
  36. for (auto i : reverse(arr)) {
  37. std::cout << i << ' ';
  38. }
  39. std::cout << std::endl;
  40.  
  41. return 0;
  42. }
Success #stdin #stdout 0s 3428KB
stdin
Standard input is empty
stdout
4 3 2 1 
4 3 2 1 
4 3 2 1