next up previous contents
Next: Add a Node: Up: The Graph Class: Previous: Iterators

Overloaded I/O and Grab and Print:

istream& operator>>(istream& in, Graph& A)
  {A.grab(in); return(in);}
istream& operator>>(istream& in, Graph* A)
  {A->grab(in); return(in);}
ostream& operator<<(ostream& out,const Graph& A)
  {A.print(out); return(out);}
ostream& operator<<(ostream& out,const Graph* A)
  {A->print(out); return(out);}
istream& Graph::grab(istream& input){}
ostream& Graph::print(ostream& output) const
{
  output << "Graph: " << endl;
  GnodePtrBagIter nit(nodes());
  if(nit){
    output << "Nodes: " << endl;
    }
  for( ; nit; ++nit){
    output << "  " << nit()->name()<<" ("<<nit()->value<<") ";
    }
  const char *p = "  Edges:  ";
  const char *q = "          ";
  for(GedgePtrBagIter eit(edges());eit;++eit){
    output << endl << p << eit()->from()->name()
           << "-----(" << eit()->weight() << ")---> "
           << eit()->to()->name();
    p = q;
    }
  output << endl << "End Graph " << endl;
  return output;
}

The grab function is currently not doing anything. Although the code in the application program could be easily adopted to input a graph by allowing users to simply enter a matrix of names and adding nodes with those names in a particular order.

The print function is defined a works as follows. A node iterator is set up using the GnodePtrBagIter class. The Iter class (be it for a node or an edge) uses the PtrBagLink class to traverse the nodes/edges. The deal is this. The BagLink class actually holds a linked list of pointers to nodes/edges. Thus, the iterator simply steps through this linked list until the next pointer is null. Later when we discuss adding a node to the graph, we will explain this in more detail. After the node iterator is set up, the nodes are traversed, and the node name and value are printed to the screen as the node is visited by the iterator. After that, the edge iterator for the graph is instantiated, and all of the edges are listed.


next up previous contents
Next: Add a Node: Up: The Graph Class: Previous: Iterators
Jim Peterson
1999-05-17