Hello,

I have a question:

Algorithm DFS(Vertex V)
	mark[V] := 1;
	print[V];
	for each (edge (V, W)) do
		if mark[W] = 0;
 			DFS(W);

I would like to realize this recursive procedure (depth-first search), but in my graph representation (with adjacency lists) I use two different classes, one for the vertex, one for the edge, like this:

class Edge;
			
class Vertex
{
	public:
		Vertex* vNext;
		char Element;
		bool marked;
		
		Edge* adjList;
		
		// Contructor...
};

class Edge
{
	public:
		Edge* eNext;
		char Element;
		bool marked;
		int weight;
		
		// Contructor...
};

So I cannot use the procedure with two different parameters (Vertex and Edge), or is there any way to preserve the recursion with different parameter types?

Thank you for your help!

There definitely is, and it is a big part of the power of C++.
What you're looking for are called "templates", there are a lot of references about it on Google but of course if something is unclear you can always post here and someone will explain ;)

Edit:
You could also improve your design. When you are writing classes in C++ you should always ask yourself "Is there any shared data between these classes" If so, you can consider using a base class and let the Vertex and Edge classes inherit from this.

You could then write your algorithm function to take a "BaseClass*" or "BaseClass&" as argument, and C++ will figure out by itself if you've passed a Vertex or an Edge.

Assume that you have a BaseClass that both Vertex and Edge inherit from in this example:

int myFunction( BaseClass* pBase )
{
   pBase->Element; 
}

int main()
{
   BaseClass* pVertex = new Vertex();
   BaseClass* pEdge   = new Edge();

   myFunction( pVertex );  // accesses pVertex->Element
   myFunction( pEdge );    // accesses pEdge->Element
}

Edited 6 Years Ago by thelamb: n/a

This article has been dead for over six months. Start a new discussion instead.