【问题标题】:Checking the matrix size检查矩阵大小
【发布时间】:2018-04-18 14:13:37
【问题描述】:

我真的不知道如何检查两个矩阵的大小,如果它们适合添加的话。 这是我的代码,目前运行没有错误:

matrix operator+(const matrix & mat){
    matrix add;
    add.mSize = mat.mSize;
    add.mP = new int[add.mSize * add.mSize];
    for(int i = 0; i < add.mSize * add.mSize; i++){
        add.mP[i] = mP[i] + mat.mP[i];
    }
    return add;                        
}

【问题讨论】:

  • 你现在不怎么写 if 语句来检查大小是否相等?
  • mPmSize 应替换为 std::vector&lt;int&gt;
  • 第一个和第二个矩阵的大小不知道怎么表示
  • 您在mP[i] + mat.mP[i] 行中访问您要添加到的类和要添加的类的mP,只需将其调整为您用于大小的成员。跨度>
  • if(mSize == mat.mSize) 谢谢

标签: c++ matrix add


【解决方案1】:

一般的二维矩阵有两个不同的维度,行和列(除非是方阵的特殊情况)。

一般情况下,您的代码可能是:

#include <stdexcept>

class matrix
{
public:
    matrix(int rows, int columns) :
        mRows(rows), mColumns(columns), mP(NULL)
    {
        mP = new double[mRows * mColumns];
        for (int i = 0; i < mRows * mColumns; i++)
            mP[i] = 0.0;
    }

    matrix(const matrix& other) :
        mRows(other.mRows), mColumns(other.mColumns), mP(NULL)
    {
        mP = new double[mRows * mColumns];
        for (int i = 0; i < mRows * mColumns; i++)
            mP[i] = other.mP[i];
    }

    ~matrix()
    {
        delete[] mP;
    }

    const double* operator[] (int row) const {
        return &mP[row * mColumns];
    }

    double* operator[] (int row) {
        return &mP[row * mColumns];
    }

    matrix& operator=(const matrix& other) {
        if (this == &other) return *this;
        if ((mRows != other.mRows) || (mColumns != other.mColumns)) throw std::invalid_argument( "dimensions don't match" );
        for (int r = 0; r < mRows; r++) {
            for (int c = 0; c < mColumns; c++) {
                (*this)[r][c] = other[r][c];
            }
        }
        return *this;
    }

    matrix& operator+=(const matrix& other) {
        if ((mRows != other.mRows) || (mColumns != other.mColumns)) throw std::invalid_argument( "dimensions don't match" );
        for (int r = 0; r < mRows; r++) {
            for (int c = 0; c < mColumns; c++) {
                (*this)[r][c] += other[r][c];
            }
        }
        return *this;
    }

private:
    int mRows;
    int mColumns;
    double *mP;
};

inline matrix operator+(matrix lhs, const matrix& rhs)
{
    lhs += rhs;
    return lhs;
}

【讨论】:

  • 不算太破旧,但是double* operator[] (int row) const在调用者手中留下了一个可以用来改变matrix内容的指针,违背了const方法的精神,而@ 987654321@已被侵犯。
  • 感谢您的提醒。修复了三法则,并稍微改进了operator[]。 TBH 实际代码将封装operator[] 返回的行,但它可能会变得太大而对本次讨论几乎没有影响。
  • 当我需要为这样的矩阵执行const 访问器时,它看起来类似于double operator()(int row, int column) const { return mP[row * mColumns + column]; } non-const 版本除了返回引用之外是相同的。 Wee 不太容易被误用。好文章在这里:isocpp.org/wiki/faq/operator-overloading#matrix-subscript-op
猜你喜欢
  • 1970-01-01
  • 2013-12-20
  • 2019-01-29
  • 2016-08-02
  • 2021-05-11
  • 1970-01-01
  • 1970-01-01
  • 2012-12-11
  • 1970-01-01
相关资源
最近更新 更多