What are the ways to assign values to a two-dimensional array in C++?

There are several ways to assign values to a two-dimensional array in C++.

  1. Assign values one by one using nested loops.
int arr[3][3];
for(int i = 0; i < 3; i++) {
    for(int j = 0; j < 3; j++) {
        arr[i][j] = i * 3 + j;
    }
}
  1. Assign values using an initialization list.
int arr[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
  1. Perform memory copy assignment using the memcpy function.
int arr1[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int arr2[3][3];
memcpy(arr2, arr1, sizeof(arr1));
  1. Use the std::copy function to copy and assign elements.
int arr1[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int arr2[3][3];
std::copy(&arr1[0][0], &arr1[0][0] + sizeof(arr1) / sizeof(int), &arr2[0][0]);

Please note that the above method applies to regular two-dimensional arrays, and for dynamically allocated two-dimensional arrays (such as when using the new operator), the assignment method will be different.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds