c++ two dimensional array into one

hay guys i need to make a two dimensional array into a one. i think i have to use recursion? thanks
Is this what you meant - the make1d( ) function below?
You can play around with function getIndex() if you want to switch rows and columns.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <iomanip>
using namespace std;

const int ROWS = 4;
const int COLS = 3;


int getIndex( int i, int j ) { return i * COLS + j; };     // returns 1d index for (i,j) point


template <class T> void make1d( T a1d[], T a2d[][COLS] )   // copy two-dimensional array a2d to a one-dimensional array a1d
{                                                          // template allows any type (int, double, string, object ...)
   for ( int i = 0; i < ROWS; i++ )
   {
      for ( int j = 0; j < COLS; j++ )
      {
         a1d[getIndex(i,j)] = a2d[i][j];                   // alternatively, could use a1d[index++] = a2d[i][j];
      }                                                    // if int index has been defined and initialised to 0
   }
   
}


// Testing
int main()
{
   int i, j;
   int index;

   int a1d[ROWS*COLS];
   int a2d[ROWS][COLS] = { { 1, 2, 3 },
                           { 4, 5, 6 },
                           { 7, 8, 9 },
                           {10,11,12 } };

   make1d<int>( a1d, a2d );


   cout << "\nOriginal 2-d array:" << endl;
   for ( i = 0; i < ROWS; i++ )
   {
      for ( j = 0; j < COLS; j++ )
      {
         cout << setw( 4 ) << a2d[i][j];
      }
      cout << endl;
   }

   cout << "\nNew 1-d array (by i,j):" << endl;
   for ( i = 0; i < ROWS; i++ )
   {
      for ( j = 0; j < COLS; j++ )
      {
         cout << setw( 4 ) << a1d[getIndex(i,j)];
      }
      cout << endl;
   }

   cout << "\nNew 1-d array (as linear array):" << endl;
   for ( int ij = 0; ij < ROWS * COLS; ij++ )
   {
      cout << setw( 4 ) << a1d[ij];
   }
}
Topic archived. No new replies allowed.