next up previous contents
Next: Overloaded I/O and Grab Up: The Graph Class: Previous: The Constructor and Destructor

Iterators

The GnodePtrBagIter and the GedgePtrBagIter classes both work in similar ways. Let's just take a look at one briefly. Consider the line

for(GnodePtrBagIter nit(d_nodes); nit; ++nit){

The first argument of the 'for' statement is a call to the iterator constructor:

GnodePtrBagIter(const GnodePtrBag& bag) : d_link_p(bag.d_root_p){};

This initializes the an iterator using the bag link pointer of the argument. This pointer is pointing to the first element of a linked list of nodes held in the bag link class. The second argument of the above 'for' statement is the 'stop' condition which is determined by the iterator function:

GnodePtrBagIter::operator const void *() const
{
  if(d_link_p==NULL) return (const void *)0;
  else return (const void *)1;
}

This returns a boolean false if the next pointer in the linked list is null. Otherwise, it returns a boolean true to indicate that there are more nodes to be traversed. That is, this function allows us to temporarily assign a true/false condition to the iterator 'nit'. Finally the last argument of the 'for' statement is the increment function. This accomplished via:

void GnodePtrBagIter::operator++()
{
  if(d_link_p!=NULL){
    if(d_link_p->d_next_p!=NULL)
      d_link_p = d_link_p->d_next_p;
    else
      d_link_p = NULL;
    }
}

This function simply gets the next node pointer in the linked list of node pointers. If there are no items left in the list, a null is returned. Thus, the stopping criteria is met and the for loop is over. As usual, we also implement overloaded istream and ostream operators via the class methods grab and print.


next up previous contents
Next: Overloaded I/O and Grab Up: The Graph Class: Previous: The Constructor and Destructor
Jim Peterson
1999-05-17