1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
|
// data structure to store graph edges
struct Edge {
int src, dest;
};
// class to represent a graph object
class Graph
{
public:
// An array of vectors to represent adjacency list
vector<int> *adjList;
// Constructor
Graph(vector<Edge> const &edges, int N)
{
// allocate memory
adjList = new vector<int>[N];
// add edges to the directed graph
for (unsigned i = 0; i < edges.size(); i++)
{
int src = edges[i].src;
int dest = edges[i].dest;
// insert at the end
adjList[src].push_back(dest);
// Uncomment below line for undirected graph
// adjList[dest].push_back(src);
}
}
// Destructor
~Graph() {
delete[] adjList;
}
};
// print adjacency list representation of graph
void printGraph(Graph const& graph, int N)
{
for (int i = 0; i < N; i++)
{
// print current vertex number
cout << "Region : "<< i << " Is Connected to : ";
// print all neighboring vertices of vertex i
for (int v : graph.adjList[i])
cout << v << " ";
cout << "\n ------------------------------------- \n" ;
}
}
vector<Edge> edges =
{
{ 0, 1 }, { 1, 2 }, { 2, 0 }, { 2, 1 },
{ 3, 2 },{ 4, 5 },{ 5, 4 },{ 5, 1 },{ 5, 2 },{ 5, 3 }
};
// Number of nodes in the graph
int N = 6;
// construct graph
Graph graph(edges, N);
// print adjacency list representation of graph
printGraph(graph, N);
Trying to read from a file :
string fileName;
int size = 0;
ifstream inputFile;
do
{
cout << "Please enter file name: ";
getline(cin, fileName);
inputFile.open(fileName.c_str());
if (!inputFile)
{
cout << "The file \"" << fileName << "\" failed to open.\n"
<< "Check to see if the file exists and please try again"
<< endl << endl;
}
while (getline(inputFile, fileName))
{
cout << fileName << '\n';
}
} while (!inputFile);
cout << size << endl << endl;
inputFile.close();
|