通过c ++ stl中的邻接列表正确实现图形

时间:2015-01-18 08:34:52

标签: c++ graph stl adjacency-list

我试图通过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 个答案:

答案 0 :(得分:1)

printf("%d->",*it)

此声明无效,因为it的类型为vector<pair<int,int> >::iterator。因此*it的类型为pair<int,int>,您无法使用期望%d的{​​{1}}进行打印。

尝试类似int

的内容

答案 1 :(得分:0)

主要问题是你不打印原点顶点的数量(它不包括在graph[i]中,但它本身是i)。 第二个错误是打印*it(一个std::pair)而不是it->first(实际的int),如Ashot所解释的那样。
一种可能性就是像这样编写最后一个循环:

    cout << endl;
    for (int i = 0; i<no_vertices; i++)
    {
        printf("%d", i);
        for (auto& e: graph[i]) {
            printf("->%d", e.first);
        }
        cout << endl;
    }    

显式使用迭代器:

cout << endl;
for (int i = 0; i<no_vertices; i++)
{
    printf("%d", i);
    vector<pair<int, int> >::iterator it = graph[i].begin();
    vector<pair<int, int> >::iterator it_end = graph[i].end();
    for (; it != it_end; it++) {
        printf("->%d", it->first);
    }
    cout << endl;
}

虽然上面的代码可以解决您的问题,但我可能没有正确解释您当前代码产生错误的原因: 由于源节点不是向量的一部分,graph[2]是一个空向量。因此,您使用ìt初始化迭代器graph[2].begin(),该graph[2].end()等于while(it+1!= graph[2].end())。 因此,

  1. 支票it+1将始终返回true(graph[2].end()将在printf("%d->",*it);后面开始一个位置)。
  2. {{1}}取消引用指向无效内存位置的指针。