更多

上三角矩阵与对称矩阵实现

C++
class UpperTriangularMatrix
{
public:
	int size;
	int length;
	UpperTriangularMatrix(int size)
	{
		this->size = size;
		length = (1 + size) * size / 2;
		a = new int[length] {0};
	}
	~UpperTriangularMatrix()
	{
		delete a;
	}
	void setValue(int position, int value)
	{
		if (position<0||position>=length)
		{
			return;
		}
		a[position] = value;
	}
	//x行标,y列标,从1开始
	void setValue(int x, int y, int value)
	{
		if (y<x)
		{
			string s = "输入的位置越界!x:" + to_string(x) + "y:" + to_string(y);
			throw exception(s.c_str());
		}
		int position = (size + size - x + 2) * (x - 1) / 2 + y - x ;
		setValue(position, value);
	}
	int getValue(int x, int y)
	{
		if (y<x)
		{
			return 0;
		}
		int position = (size + size - x + 2) * (x - 1) / 2 + y - x ;
		if (position<0||position>=length)
		{
			string s = "输入的位置越界!x:" + to_string(x) + "y:" + to_string(y);
			throw exception(s.c_str());
		}
		else
		{
			return a[position];
		}
	}
	void print()
	{
		for (int i = 1; i <= size; i++)
		{
			for (int j = 1; j <= size; j++)
			{
				cout << getValue(i, j) << "\t";
			}
			cout << endl;
		}
	}
private:
	int* a;
};
//对称矩阵
class SymmetricMatrix:public UpperTriangularMatrix
{
public:
	SymmetricMatrix(int size):UpperTriangularMatrix(size){}
	int getValue(int x, int y)
	{
		if (y<x)
		{
			return UpperTriangularMatrix::getValue(y, x);
		}
		else
		{
			return UpperTriangularMatrix::getValue(x, y);
		}
	}
	void print()
	{
		for (int i = 1; i <= size; i++)
		{
			for (int j = 1; j <= size; j++)
			{
				cout << getValue(i, j) << "\t";
			}
			cout << endl;
		}
	}
private:

};

一条评论

留下评论

您的邮箱地址不会被公开。 必填项已用 * 标注

Captcha Code