对角矩阵类(部分方法C++)

代码

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
#include<iostream>

using namespace std;

template<class T>
class diagonalMatrix {
public:
    explicit diagonalMatrix(int theN = 10);

    ~diagonalMatrix() { delete[] element; }

    [[maybe_unused]] [[nodiscard]] T get(int, int) const;

    void set(int, int, const T &);

    [[nodiscard]] int illegalParameterValue(const string &s) const {
        cout << s << endl;
        return -1;
    }

private:
    int n;
public:
    T *getElement() const;

    [[nodiscard]] int getN() const;

private:
    T *element;
};

template<class T>
diagonalMatrix<T>::diagonalMatrix(int theN) {
    // 构造函数
    // 检验theN的值是否有效
    if (theN < 1)
        throw illegalParameterValue("Matrix size must be > 0 ");
    n = theN;
    element = new T[n];
}

template<class T>
[[maybe_unused]] T diagonalMatrix<T>::get(int i, int j) const {
    // 返回矩阵中(i, j)位置上的元素
    // 检验i和j的值是否有效
    if (i < 1 || j < 1 || i > n || j > n)
        throw illegalParameterValue("matrix index out of bounds");
    if (i == j)
        return element[i - 1];
    else
        return 0;
}

// 类diagonalMatrix的方法set
template<class T>
void diagonalMatrix<T>::set(int i, int j, const T &newValue) {
    // 存储(i, j)项的新值
    // 检查i和j的值是否有效
    if (i < 1 || j < 1 || i > n || j > n)
        throw illegalParameterValue("matrix index out of bounds");
    if (i == j)
        // 存储对角值
        element[i - 1] = newValue;
    else
        // 非对角元素的值必须是0
    if (newValue != 0)
        throw illegalParameterValue("nodiagonal elements must be zero ");
}

template<class T>
T *diagonalMatrix<T>::getElement() const {
    return element;
}

template<class T>
int diagonalMatrix<T>::getN() const {
    return n;
}

template<class T>
ostream &operator<<(ostream &out, const diagonalMatrix<T> &m) {
    T *element = m.getElement();
    int N = m.getN();
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < N; ++j) {
            if (i == j)
                out << element[i] << '\t';
            else
                out << "0\t";
        }
        out << '\n';
    }

    return out;
}

int main() {

    auto mat1 = diagonalMatrix<int>(4);
    for (int i = 1; i <= 4; ++i)
        mat1.set(i, i, i);
    cout << mat1 << endl;
    return 0;
}

结果

1
2
3
4
5
C:\WINDOWS\system32\wsl.exe --distribution Debian --exec /bin/bash -c "cd /mnt/d/Documents/DataStructures/cmake-build-relwithdebinfo && /mnt/d/Documents/DataStructures/cmake-build-relwithdebinfo/diagonalMatrix"
1	0	0	0	
0	2	0	0	
0	0	3	0	
0	0	0	4