Graphs
Graphs are a fundamental data structure in computer science that represent a collection of nodes (also known as vertices) connected by edges. They are used to model relationships between objects or entities.
Graphs can be visualized as a set of points connected by lines. Each point represents a node, and the lines represent the edges connecting the nodes.
For example, imagine you want to represent the connections between different social media users. You can use a graph where each user is a node, and the relationships between users (friendships, follows, etc.) are the edges.

Graphs can be directed or undirected. In a directed graph, the edges have a specific direction, while in an undirected graph, the edges have no direction.
Graphs have various applications in computer science, including:
- Social networks and relationship modeling
- Routing algorithms in computer networks
- Recommendation systems
- Genetic algorithms
To represent a graph in C++, you can use various data structures such as adjacency matrix, adjacency list, or an edge list. The choice of data structure depends on the specific requirements of your application.
Here's an example of representing a graph using an adjacency matrix in C++:
1#include <iostream>
2#include <vector>
3using namespace std;
4
5// Function to add an edge to the graph
6void addEdge(vector<vector<int>>& graph, int u, int v) {
7 graph[u][v] = 1;
8 graph[v][u] = 1;
9}
10
11int main() {
12 int numNodes = 5;
13
14 // Create an empty graph
15 vector<vector<int>> graph(numNodes, vector<int>(numNodes, 0));
16
17 // Add edges to the graph
18 addEdge(graph, 0, 1);
19 addEdge(graph, 0, 4);
20 addEdge(graph, 1, 2);
21 addEdge(graph, 2, 3);
22 addEdge(graph, 3, 4);
23
24 cout << "Graph created successfully!";
25
26 return 0;
27}
xxxxxxxxxx
using namespace std;
int main() {
// code logic here
}