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:

Download  Run Code

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++.

Download  Run Code

Output:

1  2  3
4  5  6
7  8  9

That’s all about copying a 2-dimensional array in C++.