對稱矩陣滿足 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 後用上式。
#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))
}
#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)。下三角存儲更常用,因行優先訪問局部性更好。