I've recently been playing around with the range based for loop in gcc-4.6, and I had this idea that it'd be nice to be able to use this structure to go through a container in reverse. I've written a utility that allows you to write something like this:
Which has the expected output:Code:1 #include <iostream> 2 #include <list> 3 4 #include "reverse.hpp" 5 6 int main() 7 { 8 std::list<int> someInts; 9 for (int i = 0; i != 10; ++i) 10 someInts.push_back(i * i); 11 12 for (int v : reverse(someInts)) 13 std::cout << v << ' '; 14 15 std::cout << std::endl; 16 17 return 0; 18 }
Here's reverse.hpp:Code:81 64 49 36 25 16 9 4 1 0
I could also write shuffle() for containers with random access iterators with the same idea, although the implementation would have to be a tad more complex. It should be possible to get reverse() to work with static arrays too.Code:1 #ifndef REVERSE_HPP 2 #define REVERSE_HPP 3 4 template <typename container> 5 class reverse_wrapper 6 { 7 private: 8 container& c_; 9 10 public: 11 reverse_wrapper(container& c) : c_(c) { } 12 13 decltype(c_.rbegin()) begin() const { return c_.rbegin(); } 14 decltype(c_.rend()) end() const { return c_.rend(); } 15 }; 16 17 template <typename container> 18 class reverse_wrapper<const container> 19 { 20 private: 21 const container& c_; 22 23 public: 24 reverse_wrapper(const container& c) : c_(c) { } 25 26 decltype(c_.rbegin()) begin() const { return c_.rbegin(); } 27 decltype(c_.rend()) end() const { return c_.rend(); } 28 }; 29 30 template <typename container> 31 reverse_wrapper<container> reverse(container& c) 32 { 33 return reverse_wrapper<container>(c); 34 } 35 36 template <typename container> 37 reverse_wrapper<const container> reverse(const container& c) 38 { 39 return reverse_wrapper<const container>(c); 40 } 41 42 #endif // REVERSE_HPP
Anyone else think this is cool? Could there be a standard version of it planned that I don't know about?



LinkBack URL
About LinkBacks



