英文:
How to clone adjacency list in c++?
问题
我尝试制作一个C++邻接列表的克隆。但可能无法做到。我已经声明如下:
vector<int> adj[N]; // N是顶点的数量
我该如何在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.
答案1
得分: 3
我建议在C++中避免使用旧的C风格数组,而应仅使用std::vector
(或std::array
用于静态大小的数组)。 您的邻接表可以这样实现:
std::vector<std::vector<int>> adj(N);
这使用了接受大小的std::vector
构造函数,使N
能够是动态的(而在您的代码中,它必须在编译时已知,因为C++不支持VLA - 可变长度数组)。
克隆很容易:
std::vector<std::vector<int>> clone = adj;
如果必须使用C风格数组,您可以这样克隆它:
vector<int> clone[N];
std::copy(std::begin(adj), std::end(adj), std::begin(clone));
附注: 最好避免使用using namespace std
- 请参见这里https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice。
英文:
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 https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论