while implementing adjacency list, is the 1D vector automatically getting converted into 2D vector?

  adjacency-list, c++, graph, vector

beginner here, I was implementing an adjacency list to represent the graph in C++, I was stuck conceptually in the below code snippet.

void addEdge(vector<int> adj[], int s, int d) {
  adj[s].push_back(d);
  adj[d].push_back(s);
}

vector<int> adj[] will contain list of all nodes
My question is we have 1D vector adj[], how are we able to push multiple elements within the single-cell / index of adj[], wouldn’t that require a 2D vector like vector<vector<int>> adj[];

By pushing multiple elements I want to clarify, the adjacent vertices for that particular node will get pushed in that particular index

The entire code::

// Adjacency List representation in C++

#include <bits/stdc++.h>
using namespace std;

// Add edge
void addEdge(vector<int> adj[], int s, int d) {
  adj[s].push_back(d);
  adj[d].push_back(s);
}

// Print the graph
void printGraph(vector<int> adj[], int V) {
  for (int d = 0; d < V; ++d) {
    cout << "n Vertex "
       << d << ":";
    for (auto x : adj[d])
      cout << "-> " << x;

    printf("n");
    cout << "nsize=" << adj[d].size()<<"n";
  }
}

int main() {

  int V = 5;

  // Create a graph
  vector<int> adj[V];

  // Add edges
  addEdge(adj, 0, 1);
  addEdge(adj, 0, 2);
  addEdge(adj, 0, 3);
  addEdge(adj, 1, 2);
  printGraph(adj, V);

  cout << "nnmatrix cell"
       << adj[0][2];
}

output:

 Vertex 0:-> 1-> 2-> 3

size=3

 Vertex 1:-> 0-> 2    

size=2

 Vertex 2:-> 0-> 1    

size=2

 Vertex 3:-> 0

size=1

 Vertex 4:

size=0

Source: Windows Questions C++

LEAVE A COMMENT