Assigning a C ++ array to multiple values

therefore, when initializing an array, you can assign it several values ​​in one place:

int array [] = {1,3,34,5,6} 

but what if the array is already initialized and I want to completely replace the values ​​of the elements in this array in one line

So

 int array [] = {1,3,34,5,6} array [] = {34,2,4,5,6} 

doesn't seem to work ...

Is there any way to do this?

+45
c ++ arrays syntax programming-languages
Apr 20 2018-11-11T00:
source share
3 answers

There is a difference between initialization and assignment . What you want to do is not initialization, but purpose. But such an assignment to an array is not possible in C ++.

Here is what you can do:

 #include <algorithm> int array [] = {1,3,34,5,6}; int newarr [] = {34,2,4,5,6}; std::copy(newarr, newarr + 5, array); 



However, in C ++ 0x you can do this:

 std::vector<int> array = {1,3,34,5,6}; array = {34,2,4,5,6}; 

Of course, if you decide to use std::vector instead of a raw array.

+40
Apr 20 2018-11-11T00:
source share

You must replace the values ​​one by one, for example, to loop or copy another array over another, for example using memcpy(..) or std::copy

eg.

 for (int i = 0; i < arrayLength; i++) { array[i] = newValue[i]; } 

Make sure to ensure that the boundaries are checked correctly and any other checks that must occur to prevent a problem outside.

+6
Apr 20 2018-11-11T00:
source share
 const static int newvals[] = {34,2,4,5,6}; std::copy(newvals, newvals+sizeof(newvals)/sizeof(newvals[0]), array); 
+1
Apr 20 '11 at 15:30
source share



All Articles