In graph.addEdge, from the data file offered, this output:
Number of edges is : 3
1>3
5>2
|
Shows that "from" is 5.
At that moment, graph shows that vertex_num is 5
However, this function:
1 2 3 4
|
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w); // Add w to v’s list.
}
|
is taking in v, which is "from", at 5.
Since vertex_num is 5, the adj array was allocated to store 5 lists, which is from 0 to 4, and therefore 5 is going to cause a segmentation fault in *Nix, or a memory access error in Windows (the same thing), which fires an exception that is never caught, causing the program to terminate.
I suspect something similar is happening in the data example in your last post, where "from" is 86, but I doubt graph's adj has been allocated for 86 entries (I suspect it is 65), so the crash is similar.
I sense there are other problems, probably along similar lines, but you'll probably have to get past this one first.
To that end, consider:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
// Class to represent a graph
class Graph
{
private:
// Number of vertices
int vertex_num;
// Pointer to an array containing adjacency listsList
list<int> *adj;
//.....more material
};
Graph::Graph(int vertex_num)
{
this->vertex_num = vertex_num;
adj = new list<int>[vertex_num];
}
|
Here you're resorting to a C style allocation for adj, creating an array of lists. I submit this should probably be switched to either std::array or std::vector, to do away with C style management of this dynamic allocation.
You could, for example, create a type:
typedef std::vector< std::list< int >> adj_lists;
Or something to similar effect, creating a vector of lists. Of course, now you must use "push_back" on adj, but that's a bit smarter in my opinion, though if you still prefer to index more easily with adj.[v] instead of push_back here:
// Function to add an edge between vertices v & w
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w); // Add w to v’s list.
}
Then perhaps you'd prefer std::array.
Either way, there is some mis-alignment between vertex_num and the "from" parameter to addEdge (parameter v in the body of addEdge), as it is exceeding the size of the allocated array of lists.