Skip to content

Instantly share code, notes, and snippets.

@klmr
Created September 19, 2012 21:14
Show Gist options
  • Save klmr/3752300 to your computer and use it in GitHub Desktop.
Save klmr/3752300 to your computer and use it in GitHub Desktop.
iota iterator
template <typename T>
struct iota_iterator : std::iterator<std::random_access_iterator_tag, T> {
typedef std::iterator<std::random_access_iterator_tag, T> base_t;
typedef typename base_t::difference_type difference_type;
iota_iterator(T value = T()) : value(value) { }
iota_iterator& operator ++() {
++value;
return *this;
}
iota_iterator operator ++(int) {
iota_iterator copy = *this;
++*this;
return copy;
}
iota_iterator& operator --() {
--value;
return *this;
}
iota_iterator operator --(int) {
iota_iterator copy = *this;
--*this;
return copy;
}
iota_iterator& operator +=(difference_type n) {
value += n;
return *this;
}
iota_iterator operator +(difference_type n) {
return iota_iterator(value + n);
}
friend iota_iterator operator +(difference_type n, iota_iterator const& i) {
return i + n;
}
iota_iterator& operator -=(difference_type n) {
value -= n;
return *this;
}
iota_iterator operator -(difference_type n) {
return iota_iterator(value - n);
}
difference_type operator -(iota_iterator other) {
return value - other.value;
}
T operator [](difference_type n) const {
return value + n;
}
// Not available -- we implement a const_iterator concept.
//T& operator [](difference_type n);
T const& operator *() const {
return value;
}
T const* operator ->() const {
return &value;
}
friend bool operator ==(iota_iterator const& lhs, iota_iterator const& rhs) {
return lhs.value == rhs.value;
}
friend bool operator !=(iota_iterator const& lhs, iota_iterator const& rhs) {
return not (lhs == rhs);
}
private:
T value;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment