Question

I'm trying to figure out how to make an adjacency list, but am having trouble understanding what I need to do. I have this Java code:

public class Graph
{
 private final int V;
 private Bag<Integer>[] adj;
 public Graph(int V)
{
 this.V = V;
 adj = (Bag<Integer>[]) new Bag[V];
 for (int v = 0; v < V; v++)
 adj[v] = new Bag<Integer>();
 }
 public void addEdge(int v, int w)
 {
 adj[v].add(w);
 adj[w].add(v);
 }

But i'm trying to understand it and convert it to c++. The main part i'm unsure of is

adj = (Bag<Integer>[]) new Bag[V];
 for (int v = 0; v < V; v++)
 adj[v] = new Bag<Integer>();

Can anyone help transfer this to c++ please?

Was it helpful?

Solution

Java:

adj = (Bag<Integer>[]) new Bag[V];
 for (int v = 0; v < V; v++)
 adj[v] = new Bag<Integer>();

C++:

vector<vector<int>> adj;
for(int v=0;v<V;v++) adj.push_back(vector<int>());

Java:

 public void addEdge(int v, int w)
 {
 adj[v].add(w);
 adj[w].add(v);
 }

C++:

public void addEdge(int v, int w)
{
    adj[v].push_back(w);
    adj[w].push_back(v);
}

One more thing: BigInteger can store numbers much larger than int. But it's not necessary to use BigInteger. Because w and v in addEdge must be less than V(V is a int) or it will overflow the range of the array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top