【问题标题】:graph representation through adjacency lists using STL in c++在 C++ 中使用 STL 通过邻接表表示图形
【发布时间】: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 配置有关?

标签: c++ list vector graph stl


【解决方案1】:

对循环计数器“i”和“iter”使用后增量运算符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-29
    • 1970-01-01
    • 2013-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多