Let me first state that I just want direction, not necessarily actual code, unless a small snippet is the only way to get the point across.
I need to create a DIRECTED graph data structure using an adjacency list or matrix in C++, and add vertices/edges from standard input, which means dynamically.
I think I'd be able to create a graph fine if I was able to instantiate a set of Vertices first, then create edges and add them to the graph, but I don't understand how it is possible to add an edge which contains a vertex that hasn't been instantiated yet.
for example, the first line from standard input reads:
Miami -> New York/1100 -> Washington/1000 -> albuquerque/1700
How am I supposed to add an edge from Miami to New York if the New York vertex hasn't been added to the graph yet?
Thanks for the direction everyone!
Simple: instantiate it..
I do not see any issue with this. Assume
V
to be the vertex set seen so far.V
is initially empty. As you read the inputx->y
, you get its end points (x
andy
). If any one of them is not instantiated (i.e., not inV
), you instantiate it and add it to the vertex set.Another way to look to it: imagine we are defining the graph by its edge set
E
. By definition any edge is a pair of vertices which in turn defines the vertex set of the graph.