[英]Copying an array into another array in C++
I have an array created like this: 我有一个这样创建的数组:
std::vector<int> data(n);
I have another array b
(c Array b[]) having n int values. 我有另一个数组
b
(c Array b [])具有n个int值。 I want to put these values into data
: 我想将这些值放入
data
:
for (int i =0 ; i<n, i++) {
data[i] = b[i];
}
Is there any other method in C++ for copying an array into another arrays ? C ++中是否还有其他方法可以将一个数组复制到另一个数组中?
It's not entirely clear from your question, but if b
and data
are both std::vector<int>
, then you can do five related things: 您的问题尚不完全清楚,但是如果
b
和data
都是std::vector<int>
,那么您可以做五件相关的事情:
Initializing a new data
with b
用
b
初始化新data
std::vector<int> data = b; // copy constructor
Initializing a new data
with b
用
b
初始化新data
std::vector<int> data(begin(b), begin(b) + n); // range constructor
Copying b
entirely into an existing data
(overwriting the current data
values) 将
b
完全复制到现有data
(覆盖当前data
值)
data = b; // assignment
Copying the first n
elements of b
into an existing data
(overwriting the current data
values) 将
b
的前n
元素复制到现有data
(覆盖当前data
值)
data.assign(begin(b), begin(b) + n); // range assignment
Appending the first n
elements of b
onto an existing data
将
b
的前n
元素附加到现有data
data.insert(end(a), begin(b), begin(b) + n); // range insertion
You can also use end(b)
instead of begin(b) + n
if b
has exactly n
elements. 如果
b
恰好具有n
元素,则也可以使用end(b)
代替begin(b) + n
。 If b
is a C-style array, you can do a using std::begin;
如果
b
是C样式的数组,则可以using std::begin;
and using std::end
, and the range construction/assignment/insertion will continue to work. 并
using std::end
,范围构造/赋值/插入将继续起作用。
If b
is an int[]
(that is, a C array) then you can do: 如果
b
是int[]
(即C数组),则可以执行以下操作:
std::vector<int> data(b + 0, b + n);
If b
is also a std::vector
then you can just do: 如果
b
也是std::vector
则可以执行以下操作:
std::vector<int> data = b;
您可以使用copy
(但请确保目标向量中有足够的元素!)
copy(begin(b), end(b), begin(data))
std::vector<int> data(b, b + n);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.