如果您必须分配的空间必须是连续的,则必须分配一个“新”空间,否则内存将不连续。
看起来像这样:
int d1 = 10; // first
int d2 = 10; // second
int d3 = 10; // third dimension
int* array3D = new int[d1 * d2 * d3];
您已经为您的 3D 数组分配了足够的空间,现在必须将其映射到 3D。
array3D[(1*d1*d2) + (2*d2) + (3)]; // access element at 1,2,3
有了这个,您可以将您分配的这个 1D 数组的每个点映射到 3D 空间中的一个唯一点。
如您所见,这很容易出错。所以你永远不应该那样做。
永远不要使用 new/delete 来分配这样的数组:
使用std:array 或std::vector 为您处理此问题。
使用原始的 new/delete 会导致错误,如果分配了新的任何内容而您忘记删除它,或者您忽略了某些内容,则会出现内存泄漏。
void test(){
int* a = new int[20];
// do stuff with a...
if(error)
return; // oops this is a leak
delete a; // only executed if there was no error,
}
std::array 用于如果您知道数组在编译时必须有多大,并且永远不必更改。
另一方面,如果您在编译时不知道大小,则可以使用std::vector,它可以在您的程序运行时更改。
std::array<int, 10> test1; // creates a fixed size array of size 10 and type int.
std::vector<int> test2(10); // creates an array that can change at runtime:
test2.push_back(2); // the vector now has size 11 and the last element is equal to 2
这样你也不必delete最后的数组。
如果您希望能够在代码中更频繁地使用它,将所有这些功能包装在一个类中会非常有帮助:
#include <array>
template<typename T, std::size_t _D1, std::size_t _D2, std::size_t _D3>
class Array3D{
std::array<T, _D1*_D2*_D3> elements;
public:
std::size_t D1(){ return _D1; }
std::size_t D2(){ return _D1; }
std::size_t D3(){ return _D1; }
T& element(std::size_t d1, std::size_t d2, std::size_t d3){
return elements[(d1*_D1*_D2) + (d2*_D2) + (d3)];
}
};
int main(){ // argc/argv not required if you dont use them
Array3D<int, 10, 10, 10> array;
array.element(1,2,3) = 5;
// loop thorug all elements
// the methods d1,d2,d3 return the dimensions you gave them initialy
// this way if you cange the array size you dont have to change this loop at all
for(std::size_t i = 0; i < array.D1(); i++)
for(std::size_t j = 0; j < array.D2(); j++)
for(std::size_t k = 0; k < array.D3(); k++)
array.element(i,j,k) = 5;
// no delete
}