Created
September 12, 2014 10:59
-
-
Save 1995eaton/1654c8df1c1fde6e5f0b to your computer and use it in GitHub Desktop.
Range Iterator C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <stdexcept> | |
struct RangeIterator { | |
int64_t i, s = 1; | |
const RangeIterator &operator++() { | |
i += s; | |
return *this; | |
} | |
const bool operator!=(const RangeIterator &it) { | |
return it.i != this->i; | |
} | |
const int64_t operator*() { | |
return i; | |
} | |
RangeIterator(int64_t _i) : i(_i) {} | |
RangeIterator(int64_t _i, int64_t _s) : i(_i), s(_s) {} | |
}; | |
class range { | |
private: | |
int64_t s, e, step = 1; | |
public: | |
typedef RangeIterator iterator; | |
const iterator begin() { | |
return iterator(s, step); | |
} | |
const iterator end() { | |
return iterator(e, step); | |
} | |
range(int64_t _e) : s(0), e(_e) {} | |
range(int64_t _s, int64_t _e) : s(_s > _e ? _e : _s), e(_e) {} | |
range(int64_t _s, int64_t _e, int64_t _step) { | |
if (_step == 0) { | |
throw std::invalid_argument("step argument must not be zero"); | |
} | |
if (_step < 0 && _s < _e) { | |
_s = _e; | |
} else if (_step > 0 && _s > _e) { | |
_e = _s; | |
} | |
if (_step > 0 && _e - _s < _step) { | |
_step = _e - _s; | |
} else if (_step < 0 && _e - _s > _step) { | |
_step = _e - _s; | |
} | |
s = _s; | |
e = _e; | |
step = _step; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment