对角矩阵

对角矩阵(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.cpp

/*
 * 对角矩阵测试函数的主函数
 * 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

猜你喜欢

转载自my.oschina.net/u/1771419/blog/1818059