简体   繁体   中英

How to clone adjacency list in c++?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM