【发布时间】:2014-01-18 03:28:48
【问题描述】:
我编写了一个类,将二维数组存储为一维数组并重载索引运算符,如下所示:
inline T* operator [](const int Index) {return Data.get() + Height * Index;}
其中 Data 是 std::unique_ptr<int[]>。
这允许我这样做:MyInstance[I][J] 以行主要顺序获取值,MyInstance[J][I] 以列主要顺序获取值。
如何对 3D 数组做同样的事情?我试图弄清楚它是如何在内存中布局的,所以我做到了:
int main()
{
//index = [i + width * (j + depth * k)];
const int width = 4, height = 4, depth = 4;
int l = 0;
int ptr[width][height][depth] = {0}; //Same as int ptr[width * height * depth]; ?
//int ptr[height][width][depth]??
for (int i = 0; i < depth; ++i) //i < ??
{
for (int j = 0; j < height; ++j) //j < ??
{
for (int k = 0; k < width; ++k) //k < ??
{
ptr[i][j][k] = l++;
}
}
}
int* p = &ptr[0][0][0];
for (int i = 0; i < depth; ++i)
{
for (int j = 0; j < height; ++j)
{
for (int k = 0; k < width; ++k)
{
std::cout<<p[i + width * (j + depth * k)]<<"\n";
}
}
}
return 0;
}
但是,它没有按正确的顺序打印。它似乎以随机顺序或列主要顺序打印。
我不确定如何声明数组:
int arr[depth][height][width];
int arr[width][height][depth];
int arr[height][width][depth];
int arr[depth][width][height];
int arr[height][depth][width];
int arr[width][depth][height];
有什么想法吗?
【问题讨论】:
-
我认为您可能希望使用
std::unique_ptr<int[]>而不是std::unique_ptr<int>