I have an array created like this:
std::vector<int> data(n);
I have another array b
(c Array b[]) having n int values. I want to put these values into 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 ?
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:
Initializing a new data
with b
std::vector<int> data = b; // copy constructor
Initializing a new data
with b
std::vector<int> data(begin(b), begin(b) + n); // range constructor
Copying b
entirely into an existing data
(overwriting the current data
values)
data = b; // assignment
Copying the first n
elements of b
into an existing data
(overwriting the current data
values)
data.assign(begin(b), begin(b) + n); // range assignment
Appending the first n
elements of b
onto an existing 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. If b
is a C-style array, you can do a using std::begin;
and using std::end
, and the range construction/assignment/insertion will continue to work.
If b
is an int[]
(that is, a C array) then you can do:
std::vector<int> data(b + 0, b + n);
If b
is also a std::vector
then you can just do:
std::vector<int> data = b;
您可以使用copy
(但请确保目标向量中有足够的元素!)
copy(begin(b), end(b), begin(data))
std::vector<int> data(b, b + n);
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.