使用MxN矩阵获得意外结果

时间:2018-10-21 21:09:56

标签: c++ arrays templates matrix indexing

我有这个基本的模板矩阵类:

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矩阵扩展为MxN矩阵时:

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的回答解释了这个问题。

我想接受两个答案,但只能接受一个。谢谢你们提供的信息。我暂时不提这个问题。

2 个答案:

答案 0 :(得分:2)

如果您传递的double函数将C函数打印为{{ 1}}顺序。将2-d更改为print

答案 1 :(得分:1)

显示错误。 i是行索引,您需要将其乘以Col,而不是Row

考虑一下索引,j从0移到Col-1,因此,当您移至另一行时,需要根据此来增加索引。

相关问题