對角矩陣(diagonal):M是一個對角矩陣,則當且僅當i≠j時,M(i,j)=0。
一個rows×rows的對角矩陣D能夠表示爲 一個二維數組element[rows][rows],其中element[i-1][j-1]表示D(i,j)。
這種表示法須要rows²個數據類型爲T的數據空間。
對角矩陣最多含有rows個非0元素,所以能夠用一維數組element[rows]來表示對角矩陣,其中element[i-1]表示D(i,i)
全部未在一維數組中出現的矩陣元素均爲0.這種表示法僅僅須要rows個類型爲T的數據空間。
diagonalMatrix.cppios
/* * 對角矩陣測試函數的主函數 * diagonalMatrix.cpp */ #include<iostream> #include"diagonalmatrix.h" using namespace std; int main(void) { diagonalMatrix<int> x(20); x.set(1,1,22); x.set(5,5,44); x.set(8,5,0); cout<<x.get(5,5) <<endl; cout<<x.get(1,1) <<endl; cout<<x.get(10,1) <<endl; return 0; }
diagonalMatrix.h數組
/* * 對角矩陣 * diagonalMatrix.h */ #ifndef DIAGONALMATRIX_H #define DIAGONALMATRIX_H #include"myexceptions.h" template<class T> class diagonalMatrix { public: diagonalMatrix(int theN = 10); ~diagonalMatrix(){delete [] element;} T get(int,int) const; void set(int,int,const T&); private: int n; T* element; }; //構造函數的具體實現 template<class T> diagonalMatrix<T>::diagonalMatrix(int theN) { if(theN < 1) throw illegalParameterValue("Matrix size must be > 0"); n = theN; element = new T [n]; } //get()函數的具體實現 template<class T> T diagonalMatrix<T>::get(int i, int j) const { if(i < 1 || j < 1 || i > n || j > n) throw matrixIndexOutOfBounds(); if(i == j) return element[i - 1]; else return 0; } //set()函數的具體實現 template<class T> void diagonalMatrix<T>::set(int i, int j, const T& newValue) { if(i<1 || j < 1 || i > n || j > n) throw matrixIndexOutOfBounds(); if(i == j) element[i-1] = newValue; else if(newValue != 0) throw illegalParameterValue ("Nondiagonal elements must be zero"); } #endif // DIAGONALMATRIX_H
myExceptions.h函數
/* *異常類 *myExceptions.h */ #ifndef MYEXCEPTIONS_H #define MYEXCEPTIONS_H #include<string> using namespace std; //不合法的參數值 class illegalParameterValue { public: illegalParameterValue(string theMessage = "Illegal parameter value") { message = theMessage; } void outputMessage() { cout <<message<<endl; } private: string message; }; //數組索引不合法 class matrixIndexOutOfBounds { public: matrixIndexOutOfBounds(string theMessage = "Matrix index out of bounds") { message = theMessage; } void outputMessage() { cout << message <<endl; } private: string message; }; //數組大小不匹配 class matrixSizeMismatch { public: matrixSizeMismatch(string theMessage = "The size of the two matrics doesn't match") { message = theMessage; } void outputMessage() { cout << message <<endl; } private: string message; }; #endif // MYEXCEPTIONS_H