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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
|
// Display 2D matrix from 1D array
// Transpose elements of array so that transpose of matrix is produced.
#include <iostream>// for use of cin, cout
#include <vector>
using namespace std;
// using integer arrays
void Transpose(double* psrc, int& R, int& C)
{
double* pcopy = new double[R*C];
for(int j=0; j<R*C; j++)
pcopy[j] = psrc[j];// copy source
// overwrite source from copy
int r=0, c=0, tidx=0;
for(int j=0; j<R*C; j++)
{
r = j/C;
c = j%C;
tidx = c*R + r;
psrc[tidx] = pcopy[j];
}
delete [] pcopy;
return;
}
void ArrayOut(double* pi, int& R, int& C)
{
for(int r=0; r< R; r++)
{
for(int c=0; c< C; c++)
cout << pi[r*C+c] << " ";
cout << endl;
}
return;
}
// using vectors
void TransposeV(vector<double>& psrc, int& R, int& C)
{
vector<double> pcopy;
pcopy.resize(R*C);
for(int j=0; j<R*C; j++)
pcopy[j] = psrc[j];// copy source
// overwrite source from copy
int r=0, c=0, tidx=0;
for(int j=0; j<R*C; j++)
{
r = j/C;
c = j%C;
tidx = c*R + r;
psrc[tidx] = pcopy[j];
}
return;
}
void VectorOut(vector<double>& pi, int& R, int& C)
{
for(int r=0; r< R; r++)
{
for(int c=0; c< C; c++)
cout << pi[r*C+c] << " ";
cout << endl;
}
return;
}
int main()
{
int R=1, C=1;
cout << "Enter rows: ";
cin >> R;
cout << "Enter cols: ";
cin >> C;
cout << "using vectors" << endl << endl;
vector<double> vdbl;
vdbl.resize(R*C);
for(int j=0; j< R*C; j++)
vdbl[j] = 10+(double)j;// elements assigned sequential values for now
VectorOut(vdbl,R,C);// show as R rows, C columns
TransposeV(vdbl,R,C);// transpose elements
cout << endl;
VectorOut(vdbl,C,R);// show as C rows, R columns
cout << endl;
cout << "using dynamic arrays" << endl << endl;
double* p_dbl = new double[R*C];
for(int j=0; j< R*C; j++)
p_dbl[j] = 10+(double)j;// elements assigned here
ArrayOut(p_dbl,R,C);
Transpose(p_dbl,R,C);
cout << endl;
ArrayOut(p_dbl,C,R);
delete [] p_dbl;
system("PAUSE");
return 0;
}
|