-4

I have trying to make a clone of adjacency list in c++. But couldn't possibly do so.
I have declared using:

vector<int> adj[N]; // N is the number of vertices

How do I make the clone of this list in c++ ?

I tried looking up on the web. But couldn't find any answer. Requesting my fellow mates to answer this question.

wohlstad
  • 12,661
  • 10
  • 26
  • 39

1 Answers1

3

I recommend to avoid using old c style arrays in c++ in favor of only std::vector (or std::array for static sized arrays).
Your adjacency list could be implemented using:

std::vector<std::vector<int>> adj(N);

This is using the std::vector constructor that accepts a size, and enables N to be dynamic (whereas in your code it must be known at compile time because c++ does not support VLAs - variable length arrays).

Cloning is easy:

std::vector<std::vector<int>> clone = adj;

If you must use a c style array, you can clone it with:

vector<int> clone[N]; 
std::copy(std::begin(adj), std::end(adj), std::begin(clone));

A side note: better to avoid using namespace std - see here Why is "using namespace std;" considered bad practice?.

wohlstad
  • 12,661
  • 10
  • 26
  • 39