**三對角矩陣(tridiagonal):**M是一個三對角矩陣,當且僅當|i-j|>1時,M(i,j)=0。
在一個rows×rows的三對角矩陣中,非0元素排列在以下三條對角線上:
1)主對角線——i=j
2)主對角線之下的對角線(稱低對角線)——i=j+1
3)主對角線之上的對角線(稱高對角線)——i=j-1
這三條對角線的元素總數爲3rows-2。能夠用一個容量爲3rows-2的一維數組element來描述三對角矩陣。
tridiagonalMatrix.cppios
/* * 三對角矩陣的測試函數 * tridiagonalMatrix.cpp */ #include<iostream> #include"tridiagonalmatrix.h" using namespace std; int main(void) { tridiagonalMatrix<int> x(20); x.set(1,1,22); x.set(5,5,44); x.set(8,5,0); x.set(7,8,55); cout<< x.get(7,8)<<endl; cout << x.get(5,5) <<endl; cout << x.get(1,1) <<endl; cout << x.get(10,1) <<endl; cout << x.get(1,5) <<endl; return 0; }
tridiagonalMatrix.h數組
/* * 三對角矩陣 * tridiagonalMatrix.h */ #ifndef TRIDIAGONALMATRIX_H #define TRIDIAGONALMATRIX_H #include"myexceptions.h" using namespace std; template<class T> class tridiagonalMatrix { public: //構造函數和析構函數 tridiagonalMatrix(int theN = 10); ~tridiagonalMatrix(){delete [] element;} T get(int,int)const;//獲取元素 void set(int,int,const T&);//設置元素值 private: T* element; int n; }; /* * 類中函數的具體實現 */ //構造函數 template<class T> tridiagonalMatrix<T>::tridiagonalMatrix(int theN) { if(theN < 1) throw illegalParameterValue("Matrix size must be > 0"); n = theN; element = new T[n*3-2];//三對角數組的最大非零元素個數爲n*3-2 } //get()函數實現 template<class T> T tridiagonalMatrix<T>::get(int i, int j) const { if(i < 1 || j < 1 || i > n || j > n) throw matrixIndexOutOfBounds(); switch (i - j) { case 1: return element[i - 2]; case 0: return element[n + i - 2]; case -1: return element[2 * n + i - 2]; default: return 0; } } //set()函數的具體實現 template<class T> void tridiagonalMatrix<T>::set(int i, int j, const T& newValue) { if(i < 1 || j < 1 || i > n || j > n) throw matrixIndexOutOfBounds(); switch (i - j) { //數組存儲元素是從最下面的對角線開始存的,依次的存儲順序是: //下對角線,主對角線,上對角線 //因此纔會有下面的數組計算方式 case 1: element[i - 2] = newValue;//下對角線 break; case 0: element[n + i - 2] = newValue;//主對角線 break; case -1: element[2 * n + i - 2] = newValue;//上對角線 break; default:if(newValue != 0) throw illegalParameterValue ("non-tridiagonal elements must be zero"); break; } } #endif // TRIDIAGONALMATRIX_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