【发布时间】:2015-01-18 08:34:51
【问题描述】:
我试图通过 C++ 的 STL 中的邻接表来表示基本的无向图。这是我的代码:
#include<stdio.h>
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
int no_vertices,no_edges;
printf("Enter the no. of vertices and Edges : ");
scanf("%d%d",&no_vertices,&no_edges);
vector<pair<int,int> > graph[no_vertices];
//Pair because we edge along with its weight!!
printf("\nEnter the Edges along with their weight :");
int s,d,weight;
for(int i=0;i<no_edges;i++)
{
scanf("%d%d%d",&s,&d,&weight);
graph[s].push_back(pair<int,int>(d,weight));
}
for(int i=0;i<no_vertices;i++)
{
vector<pair<int,int> >::iterator it = graph[i].begin();
cout<<endl;
while(it+1!= graph[i].end())
{
printf("%d->",*it);
it++;
}
printf("%d",*it);
}
return 0;
}
在上面的代码中,我试图打印每个顶点及其每条边,编译器打印一些东西,然后进入一些内存错误或无限循环。例如。在上面的程序中输入 V=4 E=4 和边缘以及权重是
0 1 4
1 2 5
1 5 2
3 1 3
预期输出-
0->1
1->2->5
2
3->1
但输出是
1
2->5
然后是内存错误或无限循环。请建议对我的代码进行改进??
——
谢谢!
【问题讨论】:
标签: c++ graph stl adjacency-list