简体   繁体   中英

Graph using STL (vector of lists, i.e. Adjacency lists) - C++

I trying to solve a problem related to Graphs so I just started with representing a Graph as an adjacency list. The code is below -

#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;
}

Here is a curious thing I notice (I'm not an expert with C++11) with respect to the usage(/lack thereof) of "reserve". Or maybe it's the initialization of the list that I'm really going wrong with.

If I do this -

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

I can see that all my edges are added to the Graph vertices. However, if I do this -

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

I notice that the code just creates the graph object and breaks, without adding any edge. I get a Seg fault after executing this on Mac Bash. Has this got something to do with the usage of "reserve" where I'm not taking into account that the vector consists of a list inside?

What's the correct way to go about initializing this adjacency list?

You are confusing reserve with resize. Reserve is a kind of optimization, it only makes room to push elements in the future without having to reallocate memory. Use your first implementation of Graph constructor or change reserve by resize in the second implementation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM