**下三角矩阵(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.cpp
/*
* 下三角矩阵的测试函数
* 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