I have two method :
template <class T>
Matrix<T>::Matrix(int rows, int cols, T* data)
{
this->nRows = rows;
this->nCols = cols;
for (int i=0; i < nRows; i++)
{
vector<T> col(nCols);
for(int j=0;j<nCols;j++)
col[j]=*(data+i*nCols+j);
m.push_back(col);
}
}
And for print the matrix:
template <class T>
void Matrix<T>::Dump(void)
{
cout << "\t[\n";
for (int row=0; row<nRows; row++)
{
for (int col=0; col<nCols; col++)
cout << "\t\t" << m[row][col] << " ";
cout << "\n";
}
cout << "\t]\n";
}
And the test case is :
int M[]={1,2,3,3,4,7,2,5,8};
Matrix<int> m(3,3,M);
m.Dump();
Scenarios(In constructor) are :
for(int j=0;j<nCols;j++)
{
T val(*(data+i*nCols+j));
col.push_back(val) ;
cout<<col[j];
}
The output is all 0.
But
for(int j=0;j<nCols;j++)
{
T val(*(data+i*nCols+j));
col[j]=val ;
cout<<col[j];
}
Gives the correct result.
Please explain why pushback behaves different in both cases ?
This
line already contracts a column with all zeros in it.
In the first case you push back new value and get something like this
as the first column. So it is not surprising that
outputs zeros, because j is not bigger than 2!