-3

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.

4
  • 1
    vector<int> clone[N]; std::copy(std::begin(adj), std::end(adj), std::begin(clone)); Commented Jan 8, 2023 at 15:03
  • 7
    Use vector<vector<int>> instead, and, simply, adj2=adj? Commented Jan 8, 2023 at 15:03
  • 1
    Or std::array<std::vector<int>, N> for an array of vectors and ajd2=adj for the copy. Commented Jan 8, 2023 at 15:08
  • 4
    Don't learn C++ from garbage coding websites that teach nonsensical vector<int>[N]. Prefer a good book instead. Commented Jan 8, 2023 at 15:11

1 Answer 1

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?.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.