Implementing a Stride Iterator, You have a contiguous series of numbers and you want to iterate through the elements n at a time. - C++ template

C++ examples for template:template class

Description

Implementing a Stride Iterator, You have a contiguous series of numbers and you want to iterate through the elements n at a time.

Demo Code

#include <iterator>
#include <cassert>

template<class Iter_T>
class MyIterator/*from   www .ja  v  a 2s.c  o  m*/
{
public:
  // public typedefs
  typedef typename std::iterator_traits<Iter_T>::value_type value_type;
  typedef typename std::iterator_traits<Iter_T>::reference reference;
  typedef typename std::iterator_traits<Iter_T>::difference_type

    difference_type;
  typedef typename std::iterator_traits<Iter_T>::pointer pointer;
  typedef std::random_access_iterator_tag iterator_category;
  typedef MyIterator self;

  // constructors
  MyIterator() : m(NULL), step(0) { };
  MyIterator(const self& x) : m(x.m), step(x.step) { }
  MyIterator(Iter_T x, difference_type n) : m(x), step(n) { }

  // operators
  self& operator++() { m += step; return *this; }
  self operator++(int) { self tmp = *this; m += step; return tmp; }
  self& operator+=(difference_type x) { m += x * step; return *this; }
  self& operator--() { m -= step; return *this; }
  self operator--(int) { self tmp = *this; m -= step; return tmp; }
  self& operator-=(difference_type x) { m -= x * step; return *this; }
  reference operator[](difference_type n) { return m[n * step]; }
  reference operator*() { return *m; }

  // friend operators
  friend bool operator==(const self& x, const self& y) {
    assert(x.step == y.step);
    return x.m == y.m;
  }
  friend bool operator!=(const self& x, const self& y) {
    assert(x.step == y.step);
    return x.m != y.m;
  }
  friend bool operator<(const self& x, const self& y) {
    assert(x.step == y.step);
    return x.m < y.m;
  }
  friend difference_type operator-(const self& x, const self& y) {
    assert(x.step == y.step);
    return (x.m - y.m) / x.step;
  }
  friend self operator+(const self& x, difference_type y) {
    assert(x.step == y.step);
    return x += y * x.step;
  }
  friend self operator+(difference_type x, const self& y) {
    assert(x.step == y.step);
    return y += x * x.step;
  }
private:
  Iter_T m;
  difference_type step;
};

#include <algorithm>
#include <iterator>
#include <iostream>

using namespace std;
int main() {
  int a[] = { 0, 1, 2, 3, 4, 5, 6, 7 };
  MyIterator<int*> first(a, 2);
  MyIterator<int*> last(a + 8, 2);
  copy(first, last, ostream_iterator<int>(cout, "\n"));
}

Result


Related Tutorials