C++ 展平三维数组内部值

C++ 展平三维数组内部值,c++,arrays,C++,Arrays,我有一个扁平的3D数组,表示我试图优化的程序网格的顶点索引。我这样创建数组: int* vertIndices = new int[WIDTH * HEIGHT * DEPTH]; 并添加到数组中 vertIndices[x + WIDTH * (y + HEIGHT * z)] = vertIndex; 问题是,我只需要跟踪网格曲面上的顶点。不会创建内部顶点 因此,我创建了大量从未使用过的浪费整数 下面是一个循环,通过宽度为7、高度为7、深度为7的网格的vertIndices数组 所有这

我有一个扁平的3D数组,表示我试图优化的程序网格的顶点索引。我这样创建数组:

int* vertIndices = new int[WIDTH * HEIGHT * DEPTH];
并添加到数组中

vertIndices[x + WIDTH * (y + HEIGHT * z)] = vertIndex;
问题是,我只需要跟踪网格曲面上的顶点。不会创建内部顶点

因此,我创建了大量从未使用过的浪费整数

下面是一个循环,通过宽度为7、高度为7、深度为7的网格的vertIndices数组

所有这些-1163005939值都是位于网格内部但不会创建的顶点

我的问题是如何改进公式

x + WIDTH * (y + HEIGHT * z)
忽略内部值


谢谢

我想你不能回避在公式中引入某种条件。大概是这样的:

int getIndex(int x, int y, int z) {
    //First get the amount of points in all layers before this z layer.
    int beforeZ = (z) ? WIDTH*HEIGHT + (z - 1)*2*(WIDTH + HEIGHT - 2) : 0;

    //Then get the amount of points within this layer before this line.
    int beforeY = (y) ? WIDTH + 2*(y - 1) : 0;
    if(z == 0 || z == DEPTH - 1) beforeY = y*WIDTH;

    //And finally the amount of points within this line before this point.
    int beforeX = (x) ? 1 : 0;
    if(z == 0 || z == DEPTH - 1 || y == 0 || y == HEIGHT - 1) beforeX = x;

    //Return the amount of points before this one.
    return beforeZ + beforeY + beforeX;
}
我承认这有点难看,但我认为这已经接近你能得到的最好的了。至少如果您不想创建某种查找表来匹配坐标和索引,反之亦然。当然,这样的查找表将是真正可以处理任何情况的大炮,其缺点是内存使用量相当大,操作速度可能较慢