Copy a 2-dimensional array (matrix) in C++
This post will discuss copying a 2-dimensional array (i.e., matrix) in C++.
1. Using std::copy
The recommended solution to create a copy of a 2-dimensional array in C++ is using the std::copy function from C++ standard library. It is defined in the <algorithm> header. The following code example demonstrates the invocation of this function:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
#include <iostream> #include <algorithm> #include <iomanip> template<typename T, size_t N, size_t M> void printMatrix(T(&mat)[N][M]) { for (int i = 0; i < N; i ++ ) { for (int j = 0; j < M; j++ ) { std::cout << std::setw(2) << mat[i][j] << ' '; } std::cout << std::endl; } } int main() { const int m = 3, n = 3; int mat[m][n] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int copy[m][n]; std::copy(&mat[0][0], &mat[0][0] + m * n, ©[0][0]); printMatrix(copy); return 0; } |
Output:
1 2 3
4 5 6
7 8 9
2. Using for loop
Another option is to iterate over each row and column of the matrix using a regular for-loop and copy each element to its correct position in the destination array. This can be implemented as follows in C++.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
#include <iostream> #include <algorithm> #include <iomanip> template<typename T, size_t N, size_t M> void printMatrix(T(&mat)[N][M]) { for (int i = 0; i < N; i ++ ) { for (int j = 0; j < M; j++ ) { std::cout << std::setw(2) << mat[i][j] << ' '; } std::cout << std::endl; } } int main() { const int m = 3, n = 3; int mat[m][n] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int copy[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { copy[i][j] = mat[i][j]; } } printMatrix(copy); return 0; } |
Output:
1 2 3
4 5 6
7 8 9
That’s all about copying a 2-dimensional array in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)