2

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 ?

user2799508
  • 844
  • 1
  • 15
  • 41

4 Answers4

3

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.

TemplateRex
  • 69,038
  • 19
  • 164
  • 304
2

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;
Simple
  • 13,992
  • 2
  • 47
  • 47
1

You could use copy (but be sure that you have enough elements in the destination vector!)

copy(begin(b), end(b), begin(data))
erlc
  • 652
  • 1
  • 6
  • 11
0

std::vector<int> data(b, b + n);

EmptyData
  • 2,386
  • 2
  • 26
  • 42