0

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.

4
  • 3
    is using an std::vector<T> not an option for some reason? Commented Aug 7, 2013 at 16:17
  • @ Mgetz It could be but I want your instruction Commented Aug 7, 2013 at 16:58
  • What you're asking to do, and what you're showing in your code sample are two different things. An array cannot be "inserted" into another array. It can be copied into another array, pointed to by another array, etc. Commented Aug 7, 2013 at 17:03
  • @ Mgetz. Sorry about the mistake on the example. It is correct now. Commented Aug 7, 2013 at 17:15

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.