如何在C++中克隆邻接表?

huangapple go评论84阅读模式
英文:

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&lt;int&gt; 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&lt;std::vector&lt;int&gt;&gt; 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&lt;std::vector&lt;int&gt;&gt; clone = adj;

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

vector&lt;int&gt; 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.

huangapple
  • 本文由 发表于 2023年1月8日 23:01:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75048795.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定