通過類似這樣的 stackoverflow 執行緒,我發現您可以使用指標陣列來管理 2D 陣列。過去我使用指標來存盤二維陣列,但現在我需要將資料存盤在連續記憶體中,因此指標格式的指標不再起作用。
原始 2D 陣列是指標陣列的替代方案,但原始 2D 陣列對我不起作用,因為我希望能夠在堆中而不是在堆疊中分配存盤,因為我的容器可能非常大,我可能會遇到如果我使用香草二維陣列,堆疊溢位。
我的問題是如何為指標陣列分配記憶體。我使用new下面的運算子(請參閱我的建構式)來分配我的指標陣列
#include <iostream>
using namespace std;
template<typename DataType, unsigned numRows, unsigned numCols>
class Container2D {
public:
Container2D() {
m_data = new DataType[numRows][numCols];
}
~Container2D() {
delete [] m_data;
}
DataType* getData() { return &m_data[0][0]; }
private:
DataType (*m_data)[numCols];
};
int main() {
Container2D<int, 3, 3> container;
return 0;
}
是在堆上new DataType[numRows][numCols]分配整個二維陣列還是在堆上分配numRows指標,同時在numCols堆疊上分配 DataType 型別的物件?
在指向指標的情況下(我將存盤定義為DataType** m_data),我知道我的陣列的兩個維度都分配在堆上,我會呼叫delete m_data[i]每一列,然后呼叫delete[] m_data以釋放我的行資料。在指標陣列場景中,我不確定上面的解構式是否正確釋放資料。
uj5u.com熱心網友回復:
一種方法是使用 1D 連續陣列并實作 2D 索引到 1D 索引映射:
#include <iostream>
#include <cassert>
using namespace std;
template<typename DataType, unsigned numRows, unsigned numCols>
class Container2D {
public:
Container2D() { m_data = new DataType[numRows * numCols]; }
~Container2D() { delete [] m_data; }
inline DataType operator()(unsigned i, unsigned j) const {
assert( 0 <= i && i < numRows);
assert( 0 <= j && j < numCols);
return m_data[i*numCols j];
}
inline DataType& operator()(unsigned i, unsigned j) {
// same as above, but this allows inplace modifications
assert( 0 <= i && i < numRows);
assert( 0 <= j && j < numCols);
return m_data[i*numCols j];
}
private:
DataType* m_data;
};
int main() {
Container2D<int, 3, 3> container;
int x = container(0,0); // retrieve the element at (0,0);
container(1,2) = 9; // modify the element at (1,2);
// int y = container(3,0); // triggers assertion errors for out-of-bound indexing
return 0;
}
筆記:
- 如果
numRows并且numCols不針對特定的類實體進行更改,new則delete在這種情況下沒有必要。如果它們確實動態變化,最好將它們存盤為成員變數而不是模板引數。如果numRows和numCols太大,可以Container2D作為一個整體動態分配物件。 - 正如@GoswinvonBrederlow 評論的那樣,這與記憶體布局方面沒有區別
new m_data[numRows][numCols],但這種約定更容易擴展到更高的維度。
uj5u.com熱心網友回復:
new DataType[numRows][numCols] 是在堆上分配整個二維陣列還是在堆上分配 numRows 指標,同時在堆疊上分配 DataType 型別的 numCols 物件?
當你寫
DataType arr[numRows][numCols];
正如您提到的,記憶體將位于一個連續塊中。當您使用new. 它將分配一個指定型別的連續記憶體塊。沒有指向真實資料的隱藏指標陣列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/483993.html
下一篇:C中的陣列和指標,兩個問題
