c++graph

What does the line "list[i].push_back(adj[i][j]);" mean (in a C++ context)?


What does the following line mean?

list[i].push_back(adj[i][j]);

In:

vector<vector<int>>printGraph(int V, vector<int> adj[])
{
    vector<vector<int>>list(V);
    for(int i=0; i<V; i++)
    {
        list[i].push_back(i);
         for(int j=0; j<adj[i].size(); j++)
         {
             list[i].push_back(adj[i][j]);
         }
    }
    return list;
}

Solution

  • In your case, adj is a pointer to a vector (and in this case, I suspect it should be taken as a two-dimensional array), and list is just a vector of vectors, and therefore a two-dimensional array.

    list[i] is simply a reference to the i-th row of the array list, adj[i][j] is a reference to the value stored in cell [i][j] of the two-dimensional array adj.

    The push_back method simply adds the passed value to the end of the corresponding vector, which means the expression list[i].push_back(adj[i][j]); will simply add the value stored in the cell adj[i][j] to the end of the line list[i].