Mehdi Tanhatalab
Mehdi Tanhatalab

Reputation: 55

C++ insert 2-dimensional array of integer into another 2-dimensional array of integer

I want to insert 2-dimensional array into another 2-dimensional array- both are integer. The first one is smaller than the second then there is no error of size. The bigger have data for example to the middle of its own and second part has no data. I want to insert the second array in the middle of these data so that I need to push down the data in the bigger, meaning to copy non-zero part over the zero data. It would be appreciated if someone could offer related code in the most efficient way. for example:

int A[4][2] = {{1, 2} , {3, 4} , { 0, 0} , {0, 0} };
int B[2][2] = {{5, 6} , {7, 8}};

I want to insert B into A (between the first and second row) and push down the second row into the third row. Then we have:

 int A[4][2] = {{1, 2} ,{5, 6} , {7, 8} , {3, 4} };

I want to do this without using nested loop.

Upvotes: 0

Views: 180

Answers (1)

Chris Dodd
Chris Dodd

Reputation: 126536

Arrays in C++ are FIXED SIZE -- so there's no way 'push down' data into an array, changing its size. You can only copy stuff, overwriting (part of) the destination array, but leaving it the same size.

If you want to do this, you need to either use something (like std::vector) that allows for a changing size, or create a NEW array of the desired size and copy the data into it:

int C[6][2];
std::copy(A, A+2, C);
std::copy(B, B+2, C+2);
std::copy(A+2, A+4, C+4);

Upvotes: 2

Related Questions