0
我試圖解決與Graphs
有關的問題,所以我剛開始將圖表表示爲鄰接列表。該代碼是下面 -使用STL的圖(列表向量,即鄰接列表) - C++
#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(int nodenum=10)
{
aList.reserve(nodenum);
cout << "Created an adjacency list with "<< nodenum<< " nodes" << endl;
}
我注意到代碼只是創建圖形對象和休息,不添加任何優勢。在Mac Bash上執行此操作後,我收到Seg故障。這是否與「保留」的用法有關,我沒有考慮到矢量由內部列表組成?
有關初始化此鄰接表的正確方法是什麼?