Given an undirected or a directed graph, implement a graph data structure in C++ using STL. Implement for both weighted and unweighted graphs using the adjacency list representation of the graph.

Prerequisite:

Terminology and Representations of Graphs

 
As we already know, the adjacency list associates each vertex in the graph with the collection of its neighboring vertices or edges, i.e., every vertex stores a list of adjacent vertices. There are many variations of adjacency list representation depending upon the implementation.

Directed Graph

For example, below is the adjacency list representation of the above graph:

Adjacency List

The above representation allows the storage of additional data on the vertices but is practically very efficient when the graph contains only a few edges. We will use the STL vector class to implement the adjacency list representation of a graph.

1. Directed Graph Implementation using STL

Download  Run Code

Output:

0 ——> 1
1 ——> 2
2 ——> 0 1
3 ——> 2
4 ——> 5
5 ——> 4

2. Weighted Directed Graph Implementation using STL

We know that in a weighted graph, every edge will have a weight or cost associated with it, as shown below:

Weighted Directed Graph

Following is the C++ implementation of a weighted directed graph using STL. The implementation is similar to the above implementation of the unweighted directed graph, except here, we will also store the weight of every edge in the adjacency list.

Download  Run Code

Output:

(0, 1, 6)
(1, 2, 7)
(2, 0, 5) (2, 1, 4)
(3, 2, 10)
(4, 5, 3)
(5, 4, 1)

 
Note: We will follow the above STL representation of a graph as standard for all graph-related problems.

 
See more:

Implement Graph Data Structure in C

Graph Implementation in C++ (without using STL)

Graph Implementation in Java using Collections

Graph Implementation in Python