Difference between std::iterator, std::iterator_traits, std::random_access_iterator_tag

805 Views Asked by At

I need to write my own iterator (a random access one) for my custom container. And it is required to re-implement iterator_traits as well.

I know that std::iterator is a base class for std::iterator_traits. They are both classes. Whereas std::random_access_iterator_tag is a struct.

My first attempt is something like this: (example of this link)

#include <iostream>     // std::cout
#include <iterator>     // std::iterator, std::input_iterator_tag

class MyIterator : public std::iterator<std::random_access_tag, int>
{
  int* p;
public:
  MyIterator(int* x) :p(x) {}
  MyIterator(const MyIterator& mit) : p(mit.p) {}
  MyIterator& operator++() {++p;return *this;}
  MyIterator operator++(int) {MyIterator tmp(*this); operator++(); return tmp;}
  bool operator==(const MyIterator& rhs) const {return p==rhs.p;}
  bool operator!=(const MyIterator& rhs) const {return p!=rhs.p;}
  int& operator*() {return *p;}
};

But then I don't know where to put iterator_traits into the picture? Thanks for your time!

1

There are 1 best solutions below

1
On

you can use like this

template<class T>
class VecIter : public std::iterator<std::random_access_iterator_tag, T>
{
    public:
typedef T                                                   iterator_type;
typedef std::random_access_iterator_tag                     iterator_category;
typedef typename iterator_traits<T>::value_type             value_type;
typedef typename iterator_traits<T>::difference_type        difference_type;
        typedef typename iterator_traits<T>::pointer                pointer;
        typedef typename iterator_traits<T>::reference              reference;

}