I have never used STL-like iterators, and I am trying to figure out how to implement a very basic thing based on pointers. Once I have this class, I can change it to do more complex things. Therefore, this is the first step, and I need it to be strong in order to understand how to write your own iterators (without promotion).
I wrote the following code, and I know that it has errors. Can you help me design the random access Iterator class correctly, inspired by this:
template<Type> class Container<Type>::Iterator : public std::iterator<random_access_iterator_tag, Type> { // Lifecycle: public: Iterator() : _ptr(nullptr) {;} Iterator(Type* rhs) : _ptr(rhs) {;} Iterator(const Iterator &rhs) : _ptr(rhs._ptr) {;} // Operators : misc public: inline Iterator& operator=(Type* rhs) {_ptr = rhs; return *this;} inline Iterator& operator=(const Iterator &rhs) {_ptr = rhs._ptr; return *this;} inline Iterator& operator+=(const int& rhs) {_ptr += rhs; return *this;} inline Iterator& operator-=(const int& rhs) {_ptr -= rhs; return *this;} inline Type& operator*() {return *_ptr;} inline Type* operator->() {return _ptr;} inline Type& operator[](const int& rhs) {return _ptr[rhs];} // Operators : arithmetic public: inline Iterator& operator++() {++_ptr; return *this;} inline Iterator& operator--() {--_ptr; return *this;} inline Iterator& operator++(int) {Iterator tmp(*this); ++_ptr; return tmp;} inline Iterator& operator--(int) {Iterator tmp(*this); --_ptr; return tmp;} inline Iterator operator+(const Iterator& rhs) {return Iterator(_ptr+rhs.ptr);} inline Iterator operator-(const Iterator& rhs) {return Iterator(_ptr-rhs.ptr);} inline Iterator operator+(const int& rhs) {return Iterator(_ptr+rhs);} inline Iterator operator-(const int& rhs) {return Iterator(_ptr-rhs);} friend inline Iterator operator+(const int& lhs, const Iterator& rhs) {return Iterator(lhs+_ptr);} friend inline Iterator operator-(const int& lhs, const Iterator& rhs) {return Iterator(lhs-_ptr);} // Operators : comparison public: inline bool operator==(const Iterator& rhs) {return _ptr == rhs._ptr;} inline bool operator!=(const Iterator& rhs) {return _ptr != rhs._ptr;} inline bool operator>(const Iterator& rhs) {return _ptr > rhs._ptr;} inline bool operator<(const Iterator& rhs) {return _ptr < rhs._ptr;} inline bool operator>=(const Iterator& rhs) {return _ptr >= rhs._ptr;} inline bool operator<=(const Iterator& rhs) {return _ptr <= rhs._ptr;} // Data members protected: Type* _ptr; };
Thank you very much.
source share