简体   繁体   English

C ++中用于实现邻接列表的列表向量

[英]Vector of list in c++ for implementing adjacency lists

I am trying to implement a graph using adjacency list, using vector of lists, but the code is not compiling. 我正在尝试使用邻接列表,列表向量来实现图,但是代码未编译。

class Graph
{
    public:
        vector<list<int> > adj;
        int V;
        int E;

        Graph(int N);
        void addEdge(int u, int v);
};

Graph::Graph(int N)
{
    adj = new vector<list<int> >(N+1);
}

void Graph::addEdge(int u, int v)
{
    adj[u].push_back(v);
}

C++ is not Java or C#, you don't need to use new to create new objects. C ++不是Java或C#,您不需要使用new来创建新对象。

Instead use a member initializer list to construct the adj member: 而是使用成员初始化器列表 构造 adj成员:

Graph::Graph(int N)
    : adj(N + 1)
{
}

vector<list<int> > adj; Defines a member object of your Graph . 定义Graph的成员对象。 You don't need to use new to initialize it (this isn't Java). 您不需要使用new进行初始化(这不是Java)。 Just call the vector c'tor in the member initializer list. 只需在成员初始化器列表中调用向量c'tor即可。

Graph::Graph(int N) : adj(N+1)
{
}

Using new , you have to assign to a pointer. 使用new ,您必须分配一个指针。 I modified your code such that it now compiles fine: 我修改了您的代码,使其现在可以正常编译:

class Graph
{
    public:
        vector<list<int> > * adj;
        int V;
        int E;

        Graph(int N);
        void addEdge(int u, int v);
};

Graph::Graph(int N)
{
    adj = new vector<list<int> >(N+1);
}

void Graph::addEdge(int u, int v)
{
    (*adj)[u].push_back(v);
}

Edit 编辑

As others have pointed out, it's better to just do: 正如其他人指出的,最好这样做:

class Graph
{
public:
    vector<list<int> > adj;
    int V;
    int E;

    Graph(int N) : adj(N+1) {}
    void addEdge(int u, int v);
};

void Graph::addEdge(int u, int v)
{
    adj[u].push_back(v);
}

int main()
{
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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