对角矩阵类(部分方法C++)
代码
#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;
}
结果
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