**下三角矩陣(lower triangular):**M是一個下三角矩陣,當且僅當i<j時,M(i,j)=0
在一個n行的下三角矩陣中,非0區域的第一行有1個元素,第二行有2個元素,……第n行有個元素。
在一個上三角矩陣中,非0區域的第一行有n個元素,第二行有n-1個元素,……,第n行有1個元素。
這兩種三角形非0區域共有n(n+1)/2個非零元素。
考察一個下三角矩陣的元素L(i,j)。若是i<j,則L(i,j)=0;
若是i>=j,則L(i,j)位於非0區域。
lowerTriangularMatrix.cppios
/* * 下三角矩陣的測試函數 * lowerTriangularMatrix.cpp */ #include<iostream> #include"lowertriangularmatrix.h" using namespace std; int main(void) { lowerTriangularMatrix<int> x(20); x.set(1,1,22); x.set(5,3,44); x.set(8,5,0); x.set(10,2,55); x.set(8,5,0); cout << x.get(10,2) << endl; cout << x.get(5,3) << endl; cout << x.get(1,1) << endl; cout << x.get(10,14) << endl; cout << x.get(8,5) << endl; return 0; }
lowerTriangularMatrix.h數組
/* * 下三角矩陣的類定義 * lowerTriangularMatrix.h */ #ifndef LOWERTRIANGULARMATRIX_H #define LOWERTRIANGULARMATRIX_H #include"myexceptions.h" using namespace std; template<class T> class lowerTriangularMatrix { public: //構造函數和析構函數 lowerTriangularMatrix(int theN = 10); ~lowerTriangularMatrix(){delete [] element;} T get(int,int) const;//獲取矩陣中元素 void set(int,int,const T&);//設置矩陣元素值 private: int n;//矩陣非零元素最大個數 T *element;//矩陣中元素存儲所在數組 }; //構造函數 template<class T> lowerTriangularMatrix<T>::lowerTriangularMatrix(int theN) { if(theN < 1) throw illegalParameterValue("Matrix size must be > 0"); n = theN; element = new T [n*(n + 1)/2]; } //get()函數的實現 template<class T> T lowerTriangularMatrix<T>::get(int i, int j) const { if(i < 1 || j < 1 || i > n || j > n) throw matrixIndexOutOfBounds(); if( i >= j) //矩陣非零元素按照行主映射方式,第一行元素個數爲1,第二行爲2,……,第i行爲i //因此元素在數組中的順序應該爲i*(i-1)/2+j-1 return element[i*(i - 1)/2+j-1]; else return 0; } //set()函數的實現 template<class T> void lowerTriangularMatrix<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*(i-1)/2+j-1] = newValue; else if(newValue != 0) throw illegalParameterValue ("elements not in lower triangle must be zero"); } #endif // LOWERTRIANGULARMATRIX_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