首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++ 對稱矩陣壓縮存儲:僅存下三角/上三角實現

     編輯:關於C++

對稱矩陣特性

對稱矩陣滿足 A[i][j] == A[j][i]。只需存儲主對角線及一側三角區(下三角或上三角),空間從 n² 減為 n(n+1)/2。

壓縮映射公式(按行存儲下三角)

元素 (i, j)(i ≥ j)在一維數組中索引:

index = i*(i+1)/2 + j (0-based 索引)

訪問時若 i < j,交換 i, j 後用上式。

完整實現代碼

SymmetricMatrix.hpp


#pragma once
#include <iostream>
using namespace std;

template <class T>
class SymmetricMatrix {
public:
    // 構造函數:從二維數組構建
    SymmetricMatrix(int arry[][3], size_t n) {
        _arrySize = n * (n + 1) / 2;
        _arry = new T[_arrySize];  // 修正:new T[_arrySize] 而非 new int(_arrySize)
        size_t index = 0;
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j <= i; ++j) {  // 只存下三角(含對角線)
                _arry[index++] = arry[i][j];
            }
        }
        _matrixLen = n;
    }

    // 訪問元素(自動處理對稱性)
    T& Access(int row, int col) {
        if (row < col) swap(row, col);  // 確保 row >= col
        return _arry[row * (row + 1) / 2 + col];
    }

    ~SymmetricMatrix() { delete[] _arry; }

private:
    T* _arry;
    size_t _arrySize;
    size_t _matrixLen;
};

// 測試函數
void test() {
    int arr[3][3] = {
        { 0, 1, 2 },
        { 1, 0, 2 },
        { 2, 1, 0 }
    };
    SymmetricMatrix<int> sm(arr, 3);
    cout << sm.Access(1, 0) << endl;  // 輸出 1
    cout << sm.Access(0, 2) << endl;  // 輸出 2(自動轉為 Access(2,0))
}

main.cpp


#include <iostream>
#include "SymmetricMatrix.hpp"
using namespace std;

int main() {
    test();
    return 0;
}

關鍵修正說明

  • 原代碼 new int(_arrySize) 是分配單個 int 並初始化為 _arrySize,正確應為 new T[_arrySize] 分配數組
  • 構造函數內層循環 j <= i 而非 j < n,避免重複存儲上三角
  • 模板參數 T 應用於數組類型,原代碼構造函數參數固定為 int[][3],建議改為模板或動態分配

擴展:上三角存儲

索引公式:index = j*(j+1)/2 + i(i ≤ j),或統一用 index = n*i - i*(i-1)/2 + (j-i)。下三角存儲更常用,因行優先訪問局部性更好。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved