Skip to content

Instantly share code, notes, and snippets.

@zsol
Created July 6, 2011 07:44
Show Gist options
  • Save zsol/1066764 to your computer and use it in GitHub Desktop.
Save zsol/1066764 to your computer and use it in GitHub Desktop.
nth_iterator - an iterator wrapper that only uses every nth element returned by the underlying iterator
template <int n, typename Iterator>
class nth_iterator
{
public:
typedef typename std::iterator_traits<Iterator>::iterator_category iterator_category;
typedef typename std::iterator_traits<Iterator>::value_type value_type;
typedef typename std::iterator_traits<Iterator>::difference_type difference_type;
typedef typename std::iterator_traits<Iterator>::pointer pointer;
typedef typename std::iterator_traits<Iterator>::reference reference;
typedef Iterator iterator_type;
nth_iterator() {}
nth_iterator(const iterator_type& it)
: _it(it) {}
nth_iterator& operator++() { for (int i=0; i<n; ++i) ++_it; return *this;}
nth_iterator operator++(int) { this_type ret(*this); for (int i=0; i<n; ++i) ++_it; return ret;}
reference operator*() { return *_it; }
template <int m, typename Iterator2>
bool operator==(const nth_iterator<m, Iterator2>& other) { return _it == other._it; }
template <int m, typename Iterator2>
bool operator!=(const nth_iterator<m, Iterator2>& other) { return _it != other._it; }
private:
typedef nth_iterator<n, Iterator> this_type;
iterator_type _it;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment