class Graph {
public:
std::vector<std::vector<int>> adj;
Graph(int V) {
std::vector<std::vector<int> > adj(V, std::vector<int>());
}
void insert_edge(int v, int u);
void print_adjacencylist();
};
void Graph::insert_edge(int v, int u) {
adj[v].push_back(u);
}
I'm calling
Graph G(8);
G.insert_edge(4, 1);
and I get an error:
Debug Assertion Failed! Expression: vector subscript out of range
I'm trying to create a graph, which will have V vertices. I am using a vector of vectors to represent the graph (as an adjacency list). The nodes in my graph are numbered from 0 to V-1, so the index of the adj vector represents the number of the node. Unless I'm mistaken, adj[u] represents a vector, so I should be able to use adj[u].push_back(v) to push the vertex v into the adjacency list of the vertex u. So in my example, adj[4] should get the vector where the vertices adjacent to the node 4 are, and .push_back(1)
This is not happening. I'm thinking it has to do with me not initializing everything correctly but I've tried like a million things (even tried using a for loop to push_back a vector to each index of the adj vector) and I just keep getting the same error.