【问题标题】:Is it possible to Create a 3 dimensional array with negative numbers in C++是否可以在 C++ 中创建一个带有负数的 3 维数组
【发布时间】:2020-04-25 02:37:24
【问题描述】:

嘿,所以我目前有一个 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];
    }

}

任何帮助将不胜感激,谢谢!

【问题讨论】:

  • 嘿,所以我目前有一个 3D 对象数组,但我想让它的一半索引为负数 -- 这正在进入XY Problem 领域
  • 提示:如果你有一个指针Vox *p=new Vox[10];,你最终会得到p[0]p[9]。但是如果你添加五个:Vox *p=new Vox[10]; p += 5;,现在你有p[-5]p[4],看起来,一个带有负索引的数组。在你看来是这样吗?确实如此。它确实不是,但它是一个很好的模拟。只需将相同的原理扩展到多个维度,就可以结束了。哦,你仍然需要记住delete 得到了newed,它必须是相同的原始指针,而不是偏移量。这是一项艰巨且容易出错的工作,但这是可能的。

标签: c++ multidimensional-array dynamic-arrays


【解决方案1】:

好的,所以您需要一个具有正坐标和负坐标的 3D 笛卡尔空间。你可以写一个类来实现这个:

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() 而不是[],因为它会为您检查范围,如果超出范围则会引发异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-23
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    • 2012-12-14
    • 1970-01-01
    • 2021-11-16
    • 2022-01-01
    相关资源
    最近更新 更多