How to assign values to a two-dimensional array in C++ …
In C++, there are several ways to initialize a 2-dimensional array.
- Assign values one by one using a nested loop.
int arr[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
arr[i][j] = i + j;
}
}
- Assign values using an initialization list.
int arr[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
- Initialize all elements of the array to the same value using the memset function.
int arr[3][3];
memset(arr, 0, sizeof(arr)); // 将数组所有元素初始化为0
- Initialize all elements of the array to the same value using the fill function.
int arr[3][3];
std::fill(&arr[0][0], &arr[0][0] + sizeof(arr) / sizeof(int), 0); // 将数组所有元素初始化为0
Please choose the appropriate way to initialize and assign values to a two-dimensional array based on specific requirements.