Create An Adjancy List from Txt File

Hello,

I recently started coding in C++ and I am trying to create a graph.I looked up some tutorials and I managed to create one.It works fine when I manually input the nodes.I am trying to read a file and get the nodes from there but with no success.

Any help would be appreciated.

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();





Should I change my code ?
Last edited on
Something like this, perhaps:

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
#include <vector>
#include <map>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <string>

// general case: adjacency list where T is the type of the vertex
// for each vertex (key in the map), associate with a list of connected vertices
template< typename T > using graph_type = std::map< T, std::vector<T> > ;

template< typename T > // print a graph
std::ostream& print( const graph_type<T>& graph, std::ostream& stm = std::cout )
{
    // for each pair (vertex, list of connected vertices) in the graph
    for( const auto& pair : graph )
    {
        stm << "vertex " << pair.first << " ---> vertices [ " ;
        // print each vertex in the list of connected vertices
        for( const auto& v : pair.second ) stm << v << ' ' ;
        stm << "]\n" ;
    }

    return stm ;
}

// create a graph from data in an input stream
// eg. input of pairs of adjacent vertices of a directed graph
// 1 7 : edge from 1 -------> 7
// 2 7 : edge from 2 -------> 7
// 1 5 : edge from 1 -------> 5
// etc.
template< typename T >
graph_type<T> create( std::istream& stm )
{
    graph_type<T> graph ;

    T from, to ;
    while( stm >> from >> to ) // for each edge  'from' ---> 'to'
    {
        graph[from].push_back(to) ; // add 'to' to the set of vertices connected to 'from'

        graph[to] ; // we may not see the vertex 'to' again in the input (there may be
                   // no other edge connected to 'to'), so add it to the map right now
        // or, for an undirected graph:
        // graph[to].push_back(from) ;
    }

    /////////////////////////////////////////////////////////////////////////////////////////////////
    /// comment this out if multiple edges between the same pair of vertices are to be preserved ///
    /////////////////////////////////////////////////////////////////////////////////////////////////

    // clean up: remove duplicate entries (if any) in lists of connected vertices
    for( auto& pair : graph ) // for each pair (vertex, list of connected vertices) in the graph
    {
        auto& vec = pair.second ; // list of connected vertices
        std::sort( vec.begin(), vec.end() ) ;
        vec.erase( std::unique( vec.begin(), vec.end() ), vec.end() ) ;
    }
    /////////////////////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////////

    return graph ;
}

int main()
{
    {
        // this graph is an adjacency_list in which each vertex is identified by an int
        std::istringstream stm( "11 12   12 13   13 14   13 15   12 16   16 20   16 22\n"
                                "12 20   11 17   11 18   13 21   21 17   22 15   18 19\n"
                                "18 22   19 20   19 21   12 15   21 17   16 20   18 19\n" ) ;

        const graph_type<int> graph = create<int>(stm) ;
        print(graph) ;
    }

    std::cout << "\n------------------------------------\n\n" ;

    {
        // this graph is an adjacency_list in which each vertex is a string
        std::istringstream stm( "abc def   def ghi   ghi jkl   ghi mno   def pqr   ghi mno\n"
                                "pqr stu   def stu   abc wxy   abc ghi   wxy mno   wxy pqr\n" );

        const graph_type<std::string> graph = create<std::string>(stm) ;
        print(graph) ;
    }
}

http://coliru.stacked-crooked.com/a/51727245506605aa
Topic archived. No new replies allowed.