简体   繁体   English

在C ++中将一个数组复制到另一个数组

[英]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: 您的问题尚不完全清楚,但是如果bdata都是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: 如果bint[] (即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.

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