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

0 down vote favorite


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:

1
2
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.
Last edited on
Please give an example to illustrate what you want to do.
In the example, you have inserted 2 rows of data in the original column. Please clarify whether you want to insert entire rows/columns because inserting a single cell would not make any sense.

You will firstly have to make a few checks on the initial sizes of both matrices and check whether atleast one dimension matches.

Also, you will have to input the row/column where you want to insert.
Last edited on
You can try something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <vector>
using namespace std;

int main() {

  vector< vector<int> > A ( 4, vector<int> ( 2, 0 ) );
  vector< vector<int> > B ( 2, vector<int> ( 2, 1 ) );
  int insert_position = 1;
  vector< vector<int> >::iterator it = A.begin();
  int initial_size = A.size();

  A.insert( it + insert_position, B.begin(), B.end() );
  A.resize( initial_size );
  
  return 0;
}


EDIT: The code is just to give you an idea, haven't tried it out myself. The documentation for std::vector::insert says
Because vectors use an array as their underlying storage, inserting elements in positions other than the vector end causes the container to relocate all the elements that were after position to their new positions. This is generally an inefficient operation compared to the one performed for the same operation by other kinds of sequence containers (such as list or forward_list).
Last edited on
Topic archived. No new replies allowed.