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!
you can use like this
}