C++ 沒有內建動態多維陣列,但在堆上建立二維陣列是常見需求。本文對比 指標陣列法、單一連續塊法、std::vector 法 三大主流方案,從記憶體佈局、快取友好度、釋放便利性、現代 C++ 風格四個維度深度剖析,並給出可直接複製的範本代碼。
int **arr = new int*[rows];
for (int i = 0; i < rows; ++i)
arr[i] = new int[cols];
// 釋放
for (int i = 0; i < rows; ++i) delete[] arr[i];
delete[] arr;
// 配置
int *flat = new int[rows * cols];
// 存取:arr[row][col] → flat[row * cols + col]
auto idx = [cols](int r, int c) { return r * cols + c; };
flat[idx(2, 3)] = 42;
// 釋放
delete[] flat;
unique_ptr 完美托管// 扁平化 vector
std::vector flat(rows * cols);
flat[r * cols + c] = val;
// 或巢狀 vector(不連續,但自動管理)
std::vector> mat(rows, std::vector(cols));
mat[r][c] = val;
.data() 取得原始指標對接 C APItemplate <typename T>
class Matrix {
size_t rows_, cols_;
std::unique_ptr data_; // 或 vector
public:
Matrix(size_t r, size_t c) : rows_(r), cols_(c), data_(std::make_unique(r*c)) {}
T& operator()(size_t r, size_t c) { return data_[r * cols_ + c]; }
const T& operator()(size_t r, size_t c) const { return data_[r * cols_ + c]; }
size_t rows() const { return rows_; }
size_t cols() const { return cols_; }
T* data() { return data_.get(); }
const T* data() const { return data_.get(); }
};
vector。int** → 方案一或臨時建立指標陣列指向扁平塊。預設選擇扁平化
std::vector或std::unique_ptr<T[]>封裝類別。 只有極少數舊代碼互操作場景才手寫new[]/delete[]。
掌握這三種方案的底層機制,能讓你在效能調優、記憶體診斷、跨語言介面對接時,精準選擇最適合的資料結構佈局。