能否用C++创建一个负数的三维数组?

问题描述 投票:0回答:1

嘿,所以我目前有一个3D对象数组,但我想让它一半的索引是负的。我很确定我看到了一些关于负数组如何会导致错误和崩溃的东西,这是真的吗?

    //creates 3 dimensional array
 vGrid = new Vox * *[arraySize];
for (int x = 0; x < arraySize; x++)
{

    vGrid[x] = new Vox * [arraySize];

    for (int y = 0; y < arraySize; y++)
    {

        vGrid[x][y] = new Vox[arraySize];
    }

}

任何帮助将是非常感激的,谢谢你!

c++ multidimensional-array dynamic-arrays
1个回答
0
投票

好的,所以你想要一个具有正负坐标的三维笛卡尔空间。 你可以写一个类来实现这个功能。

class Space {
public:
    Space(int len) : _vox(len*len*len), _len(len) {}
    Vox& operator()(int x, int y, int z);
private:
    std::vector<Vox> _vox;
    int _len;
};

这将创建len^3 Vox对象,但是是在一个单一的向量中,这比C风格的指针数组更安全,更有效。

这个 operator() 是一个索引函数,可以这样使用。

Space space(51); // 3D: 51x51x51, valid indexes [-25..25]
Vox& vox = space(10, -5, 0);
// ... do things with the Vox at those coordinates

我用的是 () 而不是 [] 因为 operator[] 只能取一个参数,而我们宁愿取三个参数,以实现更自然的3D索引。 像这样实现索引操作符。

Vox& Space::operator()(int x, int y, int z)
{
    // shift the "natural" input coordinates into "storage" coordinates
    x += _len / 2; // 10 becomes 35
    y += _len / 2; // -5 becomes 20
    z += _len / 2; // 0 becomes 25
    return _vox.at(x + y*_len + z*_len*_len); // index linear storage as 3D
}

我用了 at() 而不是 [] 因为它为你检查范围,如果你超过了范围就会抛出一个异常。

© www.soinside.com 2019 - 2024. All rights reserved.