What are the ways to assign values to a C++ array?
In C++, there are several ways to assign values to an array.
- Assign values one by one: You can loop through the array and assign values to each element individually.
int arr[5];
for(int i = 0; i < 5; i++) {
arr[i] = i + 1;
}
- With the memcpy function, you can copy the values of one array into another array.
int arr1[5] = {1, 2, 3, 4, 5};
int arr2[5];
memcpy(arr2, arr1, sizeof(arr1));
- You can use the std::copy() function in the STL to copy the values of one array to another array.
int arr1[5] = {1, 2, 3, 4, 5};
int arr2[5];
std::copy(std::begin(arr1), std::end(arr1), std::begin(arr2));
- The assignment operator can be used to directly assign the values of one array to another.
int arr1[5] = {1, 2, 3, 4, 5};
int arr2[5];
for(int i = 0; i < 5; i++) {
arr2[i] = arr1[i];
}