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 ?

5
  • 1
    Do you want to copy the elements of an existing array into another existing array? std::copy does the same without a hand-made loop. Commented Jul 3, 2014 at 10:19
  • Answer can be found here using search functionality Commented Jul 3, 2014 at 10:20
  • Do you need data for anything else once you've made the copy? Commented Jul 3, 2014 at 10:23
  • If both are actually vectors rather than arrays: data = b. Commented Jul 3, 2014 at 10:24
  • @Bathsheba Yes, I will need data , as this will be processed by other functions. Commented Jul 3, 2014 at 10:29

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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;

Comments

1

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

copy(begin(b), end(b), begin(data))

Comments

0

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

1 Comment

@user2799508 just change the name

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.