我试图通过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;
}
在上面的代码中,我试图打印每个顶点及其每个边缘,编译器打印一些东西,然后进入一些内存错误或无限循环.eg . 输入上述程序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
然后是内存错误或无限循环 . 请建议改进我的代码?
谢谢!
2 回答
printf("%d->",*it)
此语句无效,因为
it
的类型为vector<pair<int,int> >::iterator
. 所以*it
的类型为pair<int,int>
,你不能使用%d
打印它,它需要int
.试试这样的东西
printf("%d %d",it->first, it->second);
主要问题是您不打印原点顶点的数量(它不包含在
graph[i]
中,但它本身是i
) . 第二个错误是打印*it
(astd::pair
)而不是it->first
(实际的int
),正如Ashot所解释的那样 .一种可能性就是像这样编写最后一个循环:
明确使用迭代器:
虽然上面的代码可以解决你的问题,但我可能没有正确解释你当前代码产生错误的原因:由于源节点不是向量的一部分,
graph[2]
是一个空向量 . 所以你用graph[2].begin()
初始化迭代器ìt
,它等于graph[2].end()
. 作为结果,检查
while(it+1!= graph[2].end())
将始终返回true(it+1
将开始一个位置BEHINDgraph[2].end()
) .printf("%d->",*it);
取消引用指向无效内存位置的指针 .