Laboratory Exercises, C++ Programming
Laboratory Exercises, C++ Programming
Laboratory Exercises, C++ Programming
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
20 Tools for Practical <strong>C++</strong> Development<br />
4.2 Graph Representation<br />
The first task is to choose a representation of the dependency graph. We will use a representation<br />
where each vertex has a list of its neighbors. This list is called an adjacency list.<br />
Consider the following makefile:<br />
D: A<br />
E: B D<br />
B: A C<br />
The dependencies in the makefile form the following graph (the graph to the left, the vertices<br />
with their adjacency lists to the right):<br />
A D<br />
B<br />
C E<br />
A graph has a list of Vertex objects (A, B, C, D, E, in the figure). A vertex is represented by an object<br />
of class Vertex, which has the attributes name (the label on the vertex) and adj (the adjacency<br />
list). In the figure, the adjacency list of vertex A contains B and D.<br />
The class definitions follow. First, class Vertex (the attribute color is used when traversing<br />
the graph, see section 4.3):<br />
class Vertex {<br />
friend class VertexList; // give VertexList access to private members<br />
private:<br />
/* create a vertex with name nm */<br />
Vertex(const std::string& nm);<br />
};<br />
std::string name; // name of the vertex<br />
VertexList adj; // list of adjacent vertices<br />
enum Color { WHITE, GRAY, BLACK };<br />
Color color; // used in the traversal algorithm<br />
In class VertexList, the adjacency list is implemented as a vector of pointers to other vertices<br />
(vptrs). The functions top sort and dfs visit are described in section 4.3.<br />
struct cyclic {}; // exception type, the graph is cyclic<br />
class VertexList {<br />
public:<br />
/* create an empty vertex list, destroy the list */<br />
VertexList();<br />
~VertexList();<br />
/* insert a vertex with the label name in the list */<br />
void add_vertex(const std::string& name);<br />
A<br />
B<br />
C<br />
D<br />
E