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.
Instead use a member initializer list to construct the adj
member:
Graph::Graph(int N)
: adj(N + 1)
{
}
vector<list<int> > adj;
Defines a member object of your Graph
. You don't need to use new
to initialize it (this isn't Java). Just call the vector c'tor in the member initializer list.
Graph::Graph(int N) : adj(N+1)
{
}
Using new
, you have to assign to a pointer. 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;
}
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.