Hello I'm trying to use the std::copy() function to copy a two dimensional array. I was wondering if it's possible to do it like so! I keep getting a "Segmentation Fault" but the array is copied correctly. I've tried subtracting a few and adding a few to the end case for the copy function, but with no success.
const int rows = 3;
const int columns = 3;
int myint[rows][columns]={{1,2,3},{4,5,6},{7,8,9}};
int favint[rows][columns];
std::copy(myint, myint+rows*columns,favint);
It's obvious that "myint+rows*columns" is incorrect, and it turns out that this value corresponds to entire rows such that "myint+rows*columns=1" means it will copy the entire first row. if "myint+rows*columns=2" it copies the first two rows etc. Can someone explain the operation of this for me?
Copying 2d Arrays Using Loopprintln(Arrays. deepToString(destination); Here, the deepToString() method is used to provide a better representation of the 2-dimensional array.
Example. public class Print2DArray { public static void main(String[] args) { final int[][] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; for (int i = 0; i < matrix. length; i++) { //this equals to the row in our matrix. for (int j = 0; j < matrix[i].
std::copy(myint, myint+rows*columns,favint);
should be:
std::copy(&myint[0][0], &myint[0][0]+rows*columns,&favint[0][0]);
prototype of std::copy
:
template< class InputIt, class OutputIt >
OutputIt copy( InputIt first, InputIt last, OutputIt d_first );
Notice that pointer to array element could be wrapper as an iterator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With