so when you initialize an array, you can assign multiple values to it in one spot:
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 that 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 a way to do so?
This question is related to
c++
arrays
programming-languages
syntax
There is a difference between initialization and assignment. What you want to do is not initialization, but assignment. But such assignment to 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 choose to use std::vector
instead of raw array.
const static int newvals[] = {34,2,4,5,6};
std::copy(newvals, newvals+sizeof(newvals)/sizeof(newvals[0]), array);
You have to replace the values one by one such as in a for-loop or copying another array over another such as using memcpy(..)
or std::copy
e.g.
for (int i = 0; i < arrayLength; i++) {
array[i] = newValue[i];
}
Take care to ensure proper bounds-checking and any other checking that needs to occur to prevent an out of bounds problem.
Source: Stackoverflow.com