Advertisement
Guest User

Python's range in C++11

a guest
Jun 12th, 2012
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.30 KB | None | 0 0
  1. #include <cstdlib>
  2. #include <iostream>
  3.  
  4. #define in :
  5.  
  6. class range
  7. {
  8.     public:
  9.  
  10.         constexpr range(int end):
  11.             _i(0),
  12.             _end(end),
  13.             _step(1),
  14.             _sup(end >= 0)
  15.         {}
  16.  
  17.         constexpr range(int begin, int end, unsigned int step=1):
  18.             _i(begin),
  19.             _end(end),
  20.             _step(step),
  21.             _sup(end >= begin)
  22.         {}
  23.  
  24.         constexpr const range& begin()
  25.         {
  26.             return *this;
  27.         }
  28.  
  29.         constexpr const range& end()
  30.         {
  31.             return *this;
  32.         }
  33.  
  34.         constexpr bool operator!=(const range&)
  35.         {
  36.             return _sup ? (_i < _end) : (_i > _end);
  37.         }
  38.  
  39.         void operator++()
  40.         {
  41.             if (_sup)
  42.             {
  43.                 _i += _step;
  44.             }
  45.             else
  46.             {
  47.                 _i -= _step;
  48.             }
  49.         }
  50.  
  51.         constexpr const int& operator*()
  52.         {
  53.             return _i;
  54.         }
  55.  
  56.     private:
  57.  
  58.         int _i;
  59.         const int _end;
  60.         const unsigned int _step;
  61.         const bool _sup;
  62. };
  63.  
  64.  
  65.  
  66. int main()
  67. {
  68.     for (const int& i in range(20, -20, 5))
  69.     {
  70.         std::cout << i << std::endl;
  71.         if (i == 30) break;
  72.     }
  73.  
  74.     return EXIT_SUCCESS;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement