'Adjacency list representation using vector of vectors(2D vector) in C++

We can fill adjacency list in BFS using 1D vector like vector<int> adj[10]; we can fill that vector as follows:

main(){
int x,y,nodes,edges;
cin>>nodes>>edges;
for(int i=0;i<edges;i++){
cin>>x>>y;
adj[x].push_back(y); //Insert y in adjacency list of x
}
}

Now how can we use 2D vector(or vector of vectors) to fill the adjacency list instead of 1D vector for 2D vector be can be like vector<vector<int> >g; So how can we populate that 2D vector for building adjacency list ?



Solution 1:[1]

vector<vector> g(nodes, vector());

g[0].push_back(3); g[1].push_back(5);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pravin Mote