这是邻接表的表示。当我尝试打印图形时,循环不会终止,并且会不断重复重复怪异的值。循环中出了什么问题
#include<iostream>
#include<list>
using namespace std;
class Graph{
int V;
list<int> *l;
public:
Graph(int v){
V=v;
l=new list<int>[V];//Array of linked lists
}
void addEdge(int u,int v, bool bidirec=true){
l[u].push_back(v);
if(bidirec){//condition for bidirectional graph
l[v].push_back(u);
}
}
void printAdjList(){
for(int i=0;i<V;i++){
cout<<i<<"-->";
for(int vertex:l[i]){//For each loop
cout<<vertex<<",";
}
cout<<endl;
}
}
};
int main(){
Graph g(5);//graph with 5 vertices
g.addEdge(0,1);//adding edges
g.addEdge(0,4);
g.addEdge(4,3);
g.addEdge(1,4);
g.addEdge(1,2);
g.addEdge(2,3);
g.printAdjList();
return 0;
}