的我有兩個方法:行爲推回
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);
}
}
而對於打印的矩陣:
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";
}
和測試用例是:
int M[]={1,2,3,3,4,7,2,5,8};
Matrix<int> m(3,3,M);
m.Dump();
方案(在構造函數中)是:
for(int j=0;j<nCols;j++)
{
T val(*(data+i*nCols+j));
col.push_back(val) ;
cout<<col[j];
}
輸出全爲0。
但
for(int j=0;j<nCols;j++)
{
T val(*(data+i*nCols+j));
col[j]=val ;
cout<<col[j];
}
給出正確的結果。
請解釋爲什麼在這兩種情況下pushback行爲有所不同?
它完全取決於col的類型。請發佈_complete_示例代碼。 – 2012-01-14 12:09:18