【发布时间】:2018-10-21 21:09:56
【问题描述】:
我有这个基本的模板矩阵类:
template<class T, unsigned N>
class Matrix {
private:
static const unsigned Stride = N;
static const unsigned Size = Stride * Stride;
T data[Size] = {};
public:
Matrix() {};
Matrix( const T* dataIn ) {
fillMatrix( dataIn );
}
void fillMatrix( const T* dataIn );
void printMatrix();
};
template<class T, unsigned N>
void Matrix<T, N>::fillMatrix( const T* dataIn ) {
for( unsigned int i = 0; i < Size; i++ ) {
this->data[i] = dataIn[i];
}
}
template<class T, unsigned N>
void Matrix<T, N>::printMatrix() {
for( unsigned int i = 0; i < Stride; i++ ) {
for( unsigned int j = 0; j < Stride; j++ ) {
std::cout << this->data[i*Stride + j] << " ";
}
std::cout << '\n';
}
}
效果很好!数据已正确填充并正确显示。但是,当我尝试将上述 Square 2D Matrix 扩展为 MxN Matrix 时:
template<class T, unsigned M, unsigned N>
class Matrix {
private:
static const unsigned Row = M;
static const unsigned Col = N;
static const unsigned Size = M * N;
T data[Size] = {};
public:
Matrix() {};
Matrix( const T* dataIn ) {
fillMatrix( dataIn );
}
void fillMatrix( const T* dataIn );
void printMatrix();
};
template<class T, unsigned M, unsigned N>
void Matrix<T,M,N>::fillMatrix( const T* dataIn ) {
for( unsigned int i = 0; i < Size; i++ ) {
this->data[i] = dataIn[i];
}
}
template<class T, unsigned M, unsigned N>
void Matrix<T,M,N>::printMatrix() {
for( unsigned int i = 0; i < Row; i++ ) {
for( unsigned int j = 0; j < Col; j++ ) {
std::cout << this->data[i*Row + j] << " ";
}
std::cout << '\n';
}
}
我没有得到正确的值:例如,如果我将 double data[6] = { 1,2,3,4,5,6 }; 这样的数组传递给此类模板,并将 Matrix<double, 2,3> 实例化为 2x3 矩阵,我将得到值和打印输出为:
1 2 3
3 4 5
我希望数据和输出是。
1 2 3
4 5 6
由于某种原因,它应用了 3 两次,而根本没有将 6 添加到矩阵中。
我是不是在 fillMatrix() 函数中错误地填充了这个 MxN 矩阵,或者在 printMatrix() 函数中通过索引显示它是否错误。我知道这是相当微不足道的,但我忽略了这一点,似乎无法找到我所缺少的。
编辑
我正在使用调试器并查看类的成员 data[Size] 并填充了正确的值,因此这让我认为或怀疑问题出在 printMatrix() 函数中。就在我这样做的时候,一些用户发布了有用的答案!一开始我的逻辑似乎是正确的,但顺序是错误的。
用户:RandomBits 的回答实际上解决了这个问题。 用户:Matthieu Brucher 的回答解释了这个问题。
我想接受两个答案,但只能接受一个。谢谢你们提供的信息。我将暂时保留这个问题。
【问题讨论】:
-
仅供参考,如果操作正确,您应该能够使用您的 1D 实现非常接近 2D 矩阵,只需执行
template<class T, size_t M, size_t N> using Matrix2D = Matrix<Matrix<T,N>,M>;或类似的操作。 -
@WhozCraig 我确信可以做到;但我正在使用后来的或第二个矩阵来回答另一个问题,所以我只是希望它简单一点。要回答他们的问题,2D 方阵还不够,所以我将其扩展为任意 MxN 矩阵,我不想在使用第一个创建后一个时造成混淆。
标签: c++ arrays templates matrix indexing