/* seq.h - Matt Mahoney, mmahoney@cs.fit.edu ANALYSIS A Seq is a fixed numeric sequence. The declaration Seq s(n, start, step); defines a sequence of elements with fixed values s[0] = start s[1] = start + step s[2] = start + step*2 ... s[n-1] = start + step*(n-1) All constructor arguments default as follows: step = 1 start = 0 n = 0 s.size() returns n. s.begin() and s.end() return Seq::const_iterator, input iterators pointing to s[0] and s[n] respectively. Seq::iterator is a synonym for Seq::const_iterator. Indexing out of bounds throws an out_of_range exception. For example: Seq s(4, 10, 2); // {10, 12, 14, 16} cout << s[1]; // 12 for (Seq::iterator p=s.begin(); p!=s.end(); ++p) cout << " " << *p // 10 12 14 16 try { s[s.size()]; // Error: s[4] } catch (out_of_range x) { cerr << "Index out of bounds\n"; } DESIGN Seq stores n, start, and step as passed to the constructor. Values for operator[] are computed as needed. Iterators are represented by a pointer to a Seq and an index. For instance, s.begin() is represented by a pointer to s and the index 0. */ #include #include template class Seq { private: int n; // size() T start, step; // Constructor parameters public: Seq(int a=0, const T& b=0, const T& c=1): n(a), start(b), step(c) {} int size() const {return n;} T operator[](int i) const { if (i<0 || i>=n) throw std::out_of_range("Seq out of range"); else return start+i*step; } // Iterators class iterator { friend class Seq; private: const Seq* p; // Current element is (*p)[i] int i; iterator(const Seq* q, int j): p(q), i(j) {} // For begin/end public: typedef std::input_iterator_tag iterator_category; typedef T value_type; typedef ptrdiff_t difference_type; typedef const T* pointer; typedef T reference; iterator(): p(0), i(0) {} iterator& operator++() {++i; return *this;} iterator operator++(int dummy) {++i; return iterator(p, i-1);} bool operator==(iterator q) const {return p==q.p && i==q.i;} bool operator!=(iterator q) const {return !(*this==q);} pointer operator->() const {static T elem; elem=(*p)[i]; return &elem;} reference operator*() const {return (*p)[i];} }; typedef iterator const_iterator; iterator begin() const {return iterator(this, 0);} iterator end() const {return iterator(this, size());} };