As far as I know, there is no such class in C ++ 11.
Anyway, I tried to improve your implementation. I made it not a template, since I do not see any advantage in creating a template. On the contrary, it has one main drawback: you cannot create a range at runtime, since you need to know the template arguments at compile time.
//your version auto x = range<m,n>(); //m and n must be known at compile time //my version auto x = range(m,n); //m and n may be known at runtime as well!
Here is the code:
class range { public: class iterator { friend class range; public: long int operator *() const { return i_; } const iterator &operator ++() { ++i_; return *this; } iterator operator ++(int) { iterator copy(*this); ++i_; return copy; } bool operator ==(const iterator &other) const { return i_ == other.i_; } bool operator !=(const iterator &other) const { return i_ != other.i_; } protected: iterator(long int start) : i_ (start) { } private: unsigned long i_; }; iterator begin() const { return begin_; } iterator end() const { return end_; } range(long int begin, long int end) : begin_(begin), end_(end) {} private: iterator begin_; iterator end_; };
Test code:
int main() { int m, n; std::istringstream in("10 20"); if ( in >> m >> n ) //using in, because std::cin cannot be used at coliru. { if ( m > n ) std::swap(m,n); for (auto i : range(m,n)) { std::cout << i << " "; } } else std::cout <<"invalid input"; }
Output:
10 11 12 13 14 15 16 17 18 19
Onine demo .
Nawaz Aug 25 2018-11-11T00: 00Z
source share