Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ 2D array to 1D array

I am attempting to convert a 2D array to 1D. I'm extremely new to C/C++ but I think it's very important to learn how to convert a 2D array to 1D. So here I am stumbling upon this problem.

My code so far is http://ideone.com/zvjKwP

#include<iostream>

using namespace std;

int main()
{

int n=0,m=0; // 2D array nRow, nCol
int a[n][m];
int i,j; // цикъл въвеждане 2D
int q,p,t; // for 2D=>1D
int b[100];
int r; // for cout
cout<<"Enter the array's number of rows and columns: ";
cin>>n>>m;

// entering values for the 2D array
    for (i = 0;i<=n;i++)
    {
        for (j = 0;j<=m;j++)
        {
            cout<<"a["<<i<<"]["<<j<<"]="<<endl;
            cin>>a[i][j];
            cin.ignore();
        }
    }

  // Most likely the failzone IMO
  for (q = 0;q<=i;q++)
    {
        for (t = 0;t<=i*j+j;t++)
        {
            b[t] = a[i][j];
        }
    }
    // attempting to print the 1D values
     cout<<"The values in the array are"<<"\n";
    for(r=0;r<=t;r++)
    {
        cout<<"b["<<r<<"] = "<<b[r]<<endl;
    }

    cin.get();
    return 0;
    }

I wrote a comment at where I think I fail.

I must also limit the numbers that get into the 1D to numbers who's value^2 is greater than 50. But for sure I must solve the problem with the conversion 2D=>1D Can you help me out?

like image 813
Anton Antonov Avatar asked Nov 11 '13 18:11

Anton Antonov


3 Answers

You are right with your supposition:

The cycle should be like:

for (q = 0; q < n; q++)
{
    for (t = 0; t < m; t++)
    {
        b[q * m + t] = a[q][t];
    }
}

It is always easier to consider such conversions from the view point of the higher dimension array. Furthermore with your code you did not actually modify i or j in the b assigning cycle, so you should not expect different values to be assigned to the different array members of b.

like image 58
Boris Strandjev Avatar answered Oct 09 '22 19:10

Boris Strandjev


http://www.cplusplus.com/doc/tutorial/arrays/

In that link look at the section on pseudo-multidimensional arrays.

I've seen many examples that that get the subscripting algorithm wrong. If in doubt, trace it out. The order of sub-scripting a 2D array should go sequentially from 0-(HEIGHT*WIDTH-1)

#define WIDTH 5
#define HEIGHT 3

int jimmy [HEIGHT * WIDTH];
int n,m;

int main ()
{
  for (n=0; n<HEIGHT; n++)
    for (m=0; m<WIDTH; m++)
    {
      jimmy[n*WIDTH+m]=(n+1)*(m+1);
    }
}
like image 24
spellmansamnesty Avatar answered Oct 09 '22 19:10

spellmansamnesty


First of all, the size of the 1D array should be n*m.

The cycle can be as follows-

int lim = n*m;

for(q = 0; q<lim; ++q) {

    b[q] = a[q/m][q%m];
}
like image 32
Shubham Avatar answered Oct 09 '22 19:10

Shubham