// Function to add an edge between two vertices
void addEdge(vector<vector<pair<int,int>>>& adj, int u, int v, int w) {
adj[u].push_back({v,w});
}
// Function to display the adjacency list
void displayAdjList(const vector<vector>& adj) {
for (int i = 0; i < adj.size(); i++) {
cout << i << ": "; // Print the vertex
for (int j : adj[i]) {
cout << "{"<<j.first << ", "<<j.second<<"}"; // Print its adjacent
}
cout << endl;
}
}
// Main function
int main() {
// Create a graph with 3 vertices and 3 edges
int V = 3;
vector<vector<pair<int,int>>> adj(V);
code
// Now add edges one by one
addEdge(adj, 1, 0, 4);
addEdge(adj, 1, 2, 3);
addEdge(adj, 2, 0, 1);
cout << "Adjacency List Representation:" << endl;
displayAdjList(adj);
return 0;
}
Correct it
Assistant
Sure, I'll help correct your C++ program for representing and displaying an adjacency list of a graph. The primary issue in your code lies in the displayAdjList function. Here's a step-by-step explanation of the corrections needed:
Type Mismatch in displayAdjList Function:
Issue: The displayAdjList function is defined to take a const vector<vector<int>>& adj, but the adjacency list adj is actually a vector<vector<pair<int, int>>>. This mismatch will result in compilation errors because you're trying to access j.first and j.second on an int, which is invalid.
Solution: Change the parameter type of displayAdjList to const vector<vector<pair<int, int>>>& to match the actual structure of the adjacency list.
Improving Readability and Ensuring Correct Output:
Enhancement: To make the output more readable, add spaces or separators between the pairs when printing the adjacency list.
Optional Enhancements:
Undirected Graph: If you intend to represent an undirected graph, ensure that edges are added in both directions.
Edge Representation: You might also consider using more descriptive variable names or comments for better code clarity.
Here's the corrected and improved version of your code:
cpp
#include <iostream>
#include <vector>
using namespace std;
// Function to add an edge between two vertices
void addEdge(vector<vector<pair<int, int>>>& adj, int u, int v, int w) {
adj[u].emplace_back(v, w);
// If the graph is undirected, uncomment the next line
// adj[v].emplace_back(u, w);
}
// Function to display the adjacency list
void displayAdjList(const vector<vector<pair<int, int>>>& adj) {
for (size_t i = 0; i < adj.size(); ++i) {
cout << i << ": ";
for (const auto& edge : adj[i]) {
cout << "{" << edge.first << ", " << edge.second << "} ";
}
cout << endl;
}
}
// Main function
int main() {
// Create a graph with 3 vertices
int V = 3;
vector<vector<pair<int, int>>> adj(V);
// Add edges: (u, v, w) represents an edge from u to v with weight w
addEdge(adj, 1, 0, 4);
addEdge(adj, 1, 2, 3);
addEdge(adj, 2, 0, 1);
cout << "Adjacency List Representation:" << endl;
displayAdjList(adj);
return 0;
}