Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guidelines to an Iterator Class

I have a Red Black tree implemented in c++. It supports the functionality of a STL map. Tree nodes contain keys and the values mapped. I want to write an iterator class for this, but I'm stuck with how to do it. Should I make it an inner class of the Tree class? Can anyone give me some guidelines on how to write it + some resources??

Thank You!!

like image 775
Izza Avatar asked Feb 03 '23 04:02

Izza


1 Answers

Sure, read this nice article on writing STL iterators, it might give you the needed overview:

http://www.drdobbs.com/184401417

In general, yes, an inner class is good, because the iterator needs access to your implementation specific tree nodes:

struct container { ...
public:
  struct iterator {
    // these typedefs are needed if you want to be STL compatible
    typedef std::forward_iterator_tag iterator_category;
    typedef T         value_type;
    typedef T*        pointer;
    typedef T&        reference;
    typedef size_t    size_type;
    typedef ptrdiff_t difference_type;

    // the element points to your implementation node
    iterator( element* init = 0 ) : current(init) {}
    T& operator*() { return current->data; } // dereference
    const T& operator*() const { return current->data; }
    iterator& operator++() { // prefix
      if ( current ) current = current->next;
      return *this;
    }
    iterator operator++(int) { // postfix
      iterator temp = *this;
      ++*this;
      return temp;
    }
    bool operator==(const iterator& x) const { return current == x.current; }
    bool operator!=(const iterator& x) const { return current != x.current; }

  private:
    // the element points to your implementation node
    element* current;
  }
  ...

The good thing here is that while the iterator is public, the element can still stay private :). And yes, the code above is STL compilant too!

like image 159
Kornel Kisielewicz Avatar answered Feb 05 '23 19:02

Kornel Kisielewicz