【发布时间】:2014-06-29 07:18:21
【问题描述】:
我正在尝试通过 c++ 中的邻接列表来表示图形。截至目前,我只想打印给定顶点附加到的顶点。我通过向量和列表来做到这一点。以下是代码
#include<iostream>
#include <vector>
#include <list>
using namespace std;
const int N=4;
int main()
{
std::vector <std::list<int> > adjList(N);
adjList[0].push_back(1);
adjList[0].push_back(2);
adjList[1].push_back(2);
adjList[1].push_back(0);
adjList[2].push_back(0);
adjList[2].push_back(1);
adjList[2].push_back(3);
adjList[3].push_back(2);
std::vector<std::list<int> >::iterator i;
int c=0;
for (std::vector<std::list<int> >::iterator i = adjList.begin(); i != adjList.end(); ++i)
{
cout<<"vertices connected to node "<< c <<"are";
std::list<int> li=*i;
for (std::list<int>::iterator iter=li.begin(); iter!=li.end();++iter)
{
cout<<*iter<<" ";
}
cout<<endl;
c++;
}
return(0);
}
代码编译正常,但没有给出任何输出。我正在使用代码块和 GNU GCC、C++ 98 编译器来编译我的代码。
【问题讨论】:
-
std::vector不会根据需要神奇地调整自身大小。您需要在修改或引用它们之前显式添加元素。 -
但是当我写 push_back 后跟括号中的元素时,我没有这样做。我是新手,所以你能详细说明一下吗
-
adjList没有元素且大小为零。adjList[0]不存在。你不能参考它。这样做是未定义的行为。您需要先向adjList添加元素。 -
@n.m.
adjList正在构建,长度为N=4。 -
@asdfg 我能够在 Linux 终端上使用 g++4.7.2 构建和运行您的代码。它打印输出就好了。也许它与您的 CodeBlocks 配置有关?