【问题标题】:Graph using STL (vector of lists, i.e. Adjacency lists) - C++使用 STL(列表向量,即邻接列表)的图形 - C++
【发布时间】:2016-11-05 23:56:51
【问题描述】:

我试图解决与 Graphs 相关的问题,所以我刚开始将 Graph 表示为邻接列表。代码如下 -

#include <iostream>
#include <list>
#include <vector>
#include <queue>
#include <stack>

using namespace std;

class Graph
{

    private:
        vector<list<int> > aList;
    public:
        Graph(int nodenum=10):aList(nodenum)
        {
            cout << "Created an adjacency list with "<< nodenum<< " nodes" << endl;
        }

        void addEdge(int from, int to)
        {
            aList[from].push_back(to);
            cout << "Executed" << endl;
        }

        int size()
        {
            return aList.size();
        }

};


int main() {

    Graph gObj(4);    // Graph's size is 4 nodes. 
    gObj.addEdge(0,1);
    gObj.addEdge(1,2);
    gObj.addEdge(2,0);
    gObj.addEdge(3,2);

    cout << "Destroyed" << endl;

    return 0;
}

关于“保留”的使用(/缺乏),我注意到了一件奇怪的事情(我不是 C++11 专家)。或者,也许这是我真正出错的列表的初始化。

如果我这样做 -

Graph(int nodenum=10):aList(nodenum)
{
       cout << "Created an adjacency list with "<< nodenum<< " nodes" << endl;
}

我可以看到我的所有边都添加到了 Graph 顶点。 但是,如果我这样做 -

Graph(int nodenum=10)
{
       aList.reserve(nodenum);
       cout << "Created an adjacency list with "<< nodenum<< " nodes" << endl;
}

我注意到代码只是创建了图形对象并中断,没有添加任何边。在 Mac Bash 上执行此操作后出现 Seg 错误。这与我没有考虑到向量由内部列表组成的“保留”的使用有关吗?

初始化这个邻接列表的正确方法是什么?

【问题讨论】:

    标签: c++ c++11 graph stl


    【解决方案1】:

    您将保留与调整大小混淆了。保留是一种优化,它只为将来推送元素腾出空间,而无需重新分配内存。 使用您的第一个 Graph 构造函数实现或通过在第二个实现中调整大小来更改保留

    【讨论】:

      猜你喜欢
      • 2011-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-30
      • 2015-06-16
      相关资源
      最近更新 更多