Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::copy two dimensional array

Tags:

c++

arrays

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?

like image 498
Matt Avatar asked Sep 10 '13 01:09

Matt


People also ask

How do I copy a 2D array into another 2D array?

Copying 2d Arrays Using Loopprintln(Arrays. deepToString(destination); Here, the deepToString() method is used to provide a better representation of the 2-dimensional array.

How do you print a two 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].


1 Answers

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.

like image 76
lulyon Avatar answered Sep 28 '22 03:09

lulyon