数据结构:5.2 对称矩阵的压缩存储

#include <iostream>
using namespace std;
class SymMatrix
{
private:
    int order;//阶数
    int *data;//存放下三角的一维数组
public:
    SymMatrix(int n)//初始化矩阵阶数
    {
        order = n;
        data= new int[(order + 1) * order / 2];
        //int num = order * (order + 1) / 2;
        //data = new int[num];
    }
    void Creat()//输入元素值
    {
        for (int i = 1; i <= order; i++)
        {
            cout << "请输入第" << i << "行元素:" << endl;
            for (int j = 1; j <= i; j++)
            {
                int index = i * (i - 1) / 2 + j - 1;
                cin >> data[index];
            }
        }
    } 
    int Get(int i, int j)//查询i行j列元素值
    {
       if (i > order || j>order ||i<1 || j < 1)
        {
            cout << "查询的位置错误" << endl;
        }
        if (i < j)
        {
            return *(data + j * (j - 1) / 2 + i - 1);
        }
        else 
        {
            return *(data + i * (i - 1) / 2 + i - 1);

        }
    }
    void Print()//输出矩阵
    {
        for (int i = 1; i <=order; i++)
        {
            for (int j = 1; j <=order; j++)
            {
                
                if (i < j)
                {
                    cout << *(data + j * (j - 1) / 2 + i - 1)<<" ";
                }
                else
                    cout << *(data + i * (i - 1) / 2 + j - 1) << " ";
            }
            cout << endl;
        }
    }
    SymMatrix Add(SymMatrix B)//对称矩阵的加法
    {
        if (order != B.order)
        {
            cout << "阶数不同,不能相加!" << endl;
            system("pause");
            exit(1);
        }
        else
            for (int i = 0; i < order; i++)
            {
                for (int j = 0; j < order; j++)
                    {
                    if (i > j)
                    {
                        cout << data[((i + 1) * i) / 2 + j] + B.data[((i + 1) * i) / 2 + j] << "  ";
                    }
                    else
                        cout << data[((j + 1) * j) / 2 + i] + B.data[((j + 1) * j) / 2 + i] << "  ";
                    }
                    cout << endl;
            }
    }
};
int main()
{
    int x;
    cout << "输入矩阵M的阶数:" << endl;
    cin >> x;
    SymMatrix M(x);
    cout << "输入矩阵M的各个元素:" << endl;
    M.Creat();
    M.Print();
    cout << "输入要查询元素的位置:" << endl;
    int i, j;
    cout << "行号:"; cin >> i;
    cout << "列号:";cin>> j;
    cout<<M.Get(i, j)<<endl;
    int y;
     cout << "输入第二个矩阵的阶数:" << endl;
    cin >> y;
    SymMatrix B(y);
    B.Creat();
    B.Print();
    cout << endl;
    B.Add(M);
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值