An Example of a Directed Graph in C++

Share.

What is a directed graph?

In mathematics, a directed graph is a set with a not necessarily symmetric binary relation, meaning given any two elements x and y in that set, if x is related to y, it is not always the case that y is related to x.

Pictorially, a directed graph is represented as nodes for the elements and arrows between the nodes for the binary relation.

An example of a directed graph in C++

In C++, you can represent a directed graph using an adjacency list. Each node in the graph will be represented by a unique identifier (e.g., an integer), and the adjacency list will store the outgoing edges for each node.

Here’s an example of a directed graph in C++ using an adjacency list:

 

#include 
#include 

using namespace std;

// Function to add an edge to the graph
void addEdge(vector<vector>& graph, int src, int dest) {
    graph[src].push_back(dest);
}

// Function to print the graph
void printGraph(const vector<vector>& graph) {
    for (int i = 0; i < graph.size(); ++i) {
        cout << "Node " << i << " -> ";
        for (int j = 0; j < graph[i].size(); ++j) {
            cout << graph[i][j] << " ";
        }
        cout << endl;
    }
}

int main() {
    int numNodes = 5; // Number of nodes in the graph
    vector<vector> graph(numNodes);

    // Adding edges to the graph
    addEdge(graph, 0, 1);
    addEdge(graph, 0, 2);
    addEdge(graph, 1, 2);
    addEdge(graph, 1, 3);
    addEdge(graph, 2, 3);
    addEdge(graph, 3, 4);

    // Printing the graph
    cout << "Directed Graph (Adjacency List):" << endl;
    printGraph(graph);

    return 0;
}  


In this example, the graph has 5 nodes (0 to 4). The addEdge function is used to add directed edges between nodes, and the printGraph function prints the adjacency list representation of the graph.

Here’s the output for the C++ program for the directed graph:

directed graph in C++