I am extending stl container with a self defined container so as to provide more flexible control on the operations of the elements
class MyContainer; template <typename T> class myiterator :public iterator<bidirectional_iterator_tag, T> { friend class MyContainer; private: T *pointer; myiterator(T *pt):pointer(pt) {} public: T& operator*() {return (*pointer);} const myiterator<T>& operator++() { pointer->current_iterator++; return *this; } bool isEnd(void) const { return pointer->current_iterator == pointer->data.end(); } }; class MyContainer { friend class myiterator<MyContainer>; public: typedef myiterator<MyContainer> iterator; typedef myiterator<MyContainer const> const_iterator; private: map<int, int> data; map<int, int>::const_iterator current_iterator; public: MyContainer() {current_iterator = data.begin(); } void addDataPair(int key, int value) {data[key] = value;} int first() const {return (*current_iterator).first;} int second() const {return (*current_iterator).second;} iterator begin() { current_iterator = data.begin(); return iterator(this); } const_iterator begin() const { return const_iterator(this); } }; This code run ok, if I use iterator as follow
MyContainer h; h.addDataPair(1, 1); h.addDataPair(2, 2); h.addDataPair(3, 3); for (MyContainer::iterator it=h.begin(); !it.isEnd(); ++it) { cout << (*it).first() << " " << (*it).second() << endl; } But it won't compile if I change iterator to const_iterator. I read some article, which mention that to define constant iterator, we simply replace the value_type from X to X const, that's how I did in my code. But I soon find that it might won't work in my case because the reference returned by an iterator is the container itself in my case. I don't know then how to make the const_iterator work without duplicate the coding.
In addition, my iterator is derived from std::iterator but I found that I cannot override the constructor for my iterator. Is that any way that I can pass more than one parameters into my iterator besides the T *pt ? Thanks.