RSS Forums RSS

Graph help please

Please support our C++ advertiser: Programming Forums
Reply
Posts: 31
Reputation: JustLearning is an unknown quantity at this point 
Solved Threads: 0
JustLearning JustLearning is offline Offline
Light Poster

Graph help please

  #1  
Nov 11th, 2008
This grap is kicking my butt. I am not sure how to do it. Can someone please help explain these to me.

  1. // graph.h
  2. // -- adjacency list representation of a weighted graph
  3. //
  4.  
  5. #ifndef GRAPH_H
  6.  
  7. #define GRAPH_H
  8.  
  9. #include <string>
  10. #include "queue.h"
  11. using namespace std;
  12.  
  13.  
  14. class FileOpenError // Exception class -- cannot open input file
  15. {
  16. };
  17.  
  18. struct EdgeNode // Structure representing an edge
  19. {
  20. int destination; // Index of destination vertex
  21. int weight; // Edge weight
  22. EdgeNode* nextPtr; // Next edge pointer
  23. };
  24.  
  25. struct VertexNode // Structure representing a vertex
  26. {
  27. string vname; // Name of vertex
  28. bool mark; // Marked flag
  29. EdgeNode* edgePtr; // Pointer to list of edges
  30. };
  31.  
  32.  
  33. class Graph // Graph ADT using adjacency list representation
  34. {
  35. private: //***** Private class members below *****//
  36. VertexNode* vertices; // Array of vertex nodes
  37. int numV; // Number of vertices
  38.  
  39. public: //***** Public members below *****//
  40. Graph(int num); // Constructor - creates graph with num vertices
  41. ~Graph(); // Destructor - deallocates all edge nodes and the vertex list
  42. void DeleteAllEdges(); // Deallocates all edge nodes from all vertices
  43. bool IsEmpty(); // Returns true if graph empty, false otherwise
  44. bool IsFull(); // Returns true if graph full, false otherwise
  45. void AddVertex(string v); // Adds vertex to graph assuming vertex not already present
  46. void AddEdge(string s, string d, int w); // Adds edge from source S to destination D with specified weight W
  47. int IndexIs(string v); // Returns index of edge from S to D; -1 if not present
  48. int WeightIs(string s, string d); // Returns weight of vertex V -- assumes V is in graph
  49. void GetToVertices(string s, Queue& q); // Returns a queue Q of vertices adjacent to vertex V
  50. void ClearMarks(); // Clears vertex marks
  51. void MarkVertex(string v); // Marks vertex V
  52. bool IsMarked(string v); // Returns true if vertex V is marked, false otherwise
  53. void Print(); // Write graph to stdout
  54. Queue* DepthFirstSearch(string startVertex, string endVertex); // Returns ptr to queue containing path or NULL if none
  55. };
  56.  
  57. void Load(string filename, Graph*& g, string& startVertex, string& endVertex);
  58. // Load graph from named file and values of start and end vertices
  59. // Note: this file attempts to open the named file for input and input all information.
  60. // If the file fails to open, Load throws the FileOpenError exception
  61.  
  62. #endif
  63.  

This is what I have so far but I don't think this is right. Can someone please explain these functions I just don't get it.

  1. #include <iostream>
  2. #include <new>
  3. #include <cstddef>
  4. #include <string>
  5. #include "graph.h"
  6.  
  7. using namespace std;
  8.  
  9. Graph::Graph(int num)
  10. {
  11. numV = 0;
  12. vertices[num];
  13. }
  14.  
  15. Graph::~Graph()
  16. {
  17. delete [] vertices;
  18. }
  19.  
  20. bool Graph::IsEmpty()
  21. {
  22. return (numV == 0);
  23. }
  24.  
  25. bool Graph::IsFull()
  26. {
  27. EdgeNode* tempPtr;
  28. try
  29. {
  30. tempPtr = new EdgeNode;
  31. }
  32. catch (bad_alloc)
  33. {
  34. return true;
  35. }
  36. delete tempPtr;
  37. return false;
  38. }
  39.  
  40. void Graph::AddVertex(string v)
  41. {
  42. verticies[numV] = v;
  43.  
  44. for(int index = 0; index < numV; index++)
  45. {
  46.  
  47. }
AddThis Social Bookmark Button
Reply With Quote  
Posts: 947
Reputation: Alex Edwards is a jewel in the rough Alex Edwards is a jewel in the rough Alex Edwards is a jewel in the rough Alex Edwards is a jewel in the rough 
Solved Threads: 106
Alex Edwards's Avatar
Alex Edwards Alex Edwards is offline Offline
Posting Shark

Re: Graph help please

  #2  
Nov 11th, 2008
It might help if you explain what your Graph-class is supposed to do.

By the way, what is your constructor definition supposed to do?

You assign numV to be 0 then you de-reference an uninitialized array of vertices.

You probably meant to do something like this--

  1. Graph::Graph(int num) : numV(num), vertices(new VertexNode[num]){
  2.  
  3. memset (vertices, 0, sizeof(VertexNode) * num);
  4. }

-- the numV looks like it represents the total number of VertexNodes (or vertices) and it is initialized via pre-initialization, along with your pointer to VertextNodes.

The memset in the constructor body is necessary because by calling new you are invoking the default constructor of an instance of a class ( or struct or union in C++ ) in which it is typically the responsibility of the that constructor to initialize members of the object. However, because your struct of type VertexNode has no constructor you have to explicitly set the values inside the struct. A good way of doing so is by using memset. In the above code the memset sets the bit-value of every byte for each VertexNode to zero, so everything has a value of 0 in your struct.

So this means...

  1. struct VertexNode // Structure representing a vertex
  2. {
  3. string vname; // Name of vertex
  4. bool mark; // Marked flag
  5. EdgeNode* edgePtr; // Pointer to list of edges
  6. };
  7.  

*string's members are set to zero (the backing char-pointer a string has is likely to point to null),
as well as any other members in the string object.

*bool is set to false (because 0 is false and any other number is true)

*EdgeNode points to null (size of pointer is typically 4-8 bytes, depending on the machine (might be more on some machines but lets assume 8 bytes), so lets assume each byte's character determines where the EdgeNode is pointing to. If the bytes are set to zero, then the only location EdgeNode is pointing to is NULL, or location 0x00000000 where each 0 (except the first one followed by an x) represents the value of the location in bytes via hexidecimal).

This should happen to each element in your array sense memory is being set for not just one VertexNode, but the amount that is pre-initialized.

That's probably overkill for an explanation of the choice of initialization for your array of values but hopefully it helps @_@.

Note: It may be better to migrate the initialization of your numV and VertexNode pointer to the body of the constructor so you can catch an out-of-memory error. This way if an error occurs and memory cant be assigned to the VertexNode pointer, your application wont crash for attempting to 'initialize' memory that may not belong to it.

Linkage
Last edited by Alex Edwards : Nov 11th, 2008 at 11:37 pm.
Reply With Quote  
Posts: 31
Reputation: JustLearning is an unknown quantity at this point 
Solved Threads: 0
JustLearning JustLearning is offline Offline
Light Poster

Re: Graph help please

  #3  
Nov 12th, 2008
Sorry to be so vague but here are my instructions.

I understand what a graph is but I just dont know how to impliment it.

Your main function must perform all of the following tasks.
(1) Declare a string variable and initialize it with the value argv[1].
(2) Invoke the Load function to input graph data from file along with the search start and end vertices.
Since Load may throw an exception, you should use a try-catch pair to trap the exception.
(3) Once the graph loads, use the Graph class Print function to print out the graph
(4) Perform a Depth-First Search using the start and end vertices input from the file by the Load
function. The path, if found, is stored in a queue (whose address is returned by the DFS function) so
use the Queue class Print function to print out the path. If no path is found, a NULL pointer is
returned by the DFS function.
(5) Compute the weight of the path found by DFS and output to monitor.
Your program must also contain appropriate comments in order to receive full credit.
Your goal is to EXACTLY match the output of your program to that of the sample solution.
Fall 2008 CPE212 Project Assignment Project 8
Page 4 of 5
<Project08 Input File Format>
Use the extraction operator for all inputs!!!
First line of file contains an integer specifying the total number of vertices in the graph.
Use this value when you call the constructor to create the graph.
‘v’  followed by vertex_name (vertex names are always single-word strings)
‘u’  an UNDIRECTED EDGE followed by vertex1 vertex2 edge_weight
‘d’  a DIRECTED EDGE followed by source_vertex destination_vertex edge_weight
‘s‘  name of dfs_start_vertex
‘e’  name of dfs_end_vertex
Hints:
- Use the extraction operator for all inputs!!!
- An UNDIRECTED EDGE may be simulated by two DIRECTED EDGES going in
opposite directions with the same weights
<Project 8 Graph Class Description>
The Graph class uses an Adjacency List Representation to store the graph information.
 Inline functions are not allowed in this course and will result in no credit (0) 
[Note: An inline function is a function whose definition appears within the class declaration]
Attribute Name Data Type Purpose
vertices VertexNode* Stores address of dynamically allocated array of VertexNodes
numV int Number of vertices
Function Name Return
Type
Purpose
Graph N/A Constructor that allocates an array of VertexNodes just large
enough to hold incoming graph
DeleteAllEdges void Deallocates all EdgeNodes connected to all vertices
IsEmpty bool Returns true if Graph is empty, false otherwise
IsFull bool Returns true if Graph is full, false otherwise
AddVertex void Adds vertex name V to vertex array
AddEdge void Adds edge from Source to Destination with specified Weight
IndexIs int Scans vertex array to locate named vertex and returns array index
WeightIs int Returns weight of edge from Source to Destination
GetToVertices void Returns a queue of vertices adjacent to specified vertex
ClearMarks void Sets all vertex marks to false
Fall 2008 CPE212 Project Assignment Project 8
Page 5 of 5
MarkVertex void Sets mark of specified vertex to true
IsMarked bool Returns mark status of specified vertex
Print void Prints Graph contents in specified format (see sample solution)
DepthFirstSearch Queue* Returns pointer to a queue containing the path if found. If not
found, returns NULL pointer
~Graph N/A Deallocates all edge nodes and the vertex array
Note: Load function described in “graph.h”
 See the file graph.h for additional details regarding the function interfaces 
Reply With Quote  
Reply

Only community members can participate in forum threads. You must register or log in to contribute.



Similar Threads
Other Threads in the C++ Forum
Views: 540 | Replies: 2 | Currently Viewing: 1 (0 members and 1 guests)

 

Thread Tools Display Modes
Forums | Blogs | Tutorials | Code Snippets | Whitepapers | RSS Feeds | Advertising
All times are GMT -4. The time now is 2:30 pm.
Newsletter Archive - Sitemap - Privacy Statement - Acceptable Use Policy - Contact Us
Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC