C ,如何制作动态3D矩阵

C++, how can I make a dynamic 3D matrix?

本文关键字:3D 矩阵 动态 何制作      更新时间:2023-10-16

in c ,CodeBlocks环境,我声明:

int m[120][120][120];

我知道,从m[0][0][0]m[119][119][119],我都有变量。

我可以让计算机从位置宣布内存m[45][45][45]

我希望我清楚自己:)

如果您只需要45..119,只需使矩阵45在每个维度中较小并转换值

// Very simple example to explain what I meant.
class MyMatrix
{
    public:
        SetValue(int x, int y, int z, float value) { mMatrix[x-45][y-45][z-45] = value; }
    private
        float mMatrix[120-45][120-45][120-45];
}

您所说的是基本上是在开始时要保留/分配一些内存,如果以后您需要更多内存,则希望将其扩展。

如果是这种情况,则最好使用std::vector,然后将45作为初始容量。通常45太小,但是如果您想设置它,则可以通过std::vector.reserve(n)方法进行操作。会这样:

matrix = vector<vector<vector<float> > >();
matrix.reserve(45);
for (int i = 0; i < 45; i++)
{
    matrix[i] = vector<vector<float> >()
    matrix[i].reserve(45);
    for (int j = 0; j < 45; j++)
    {
        matrix[i][j] = vector<float>();
        matrix[i][j].reserve(45);
    }
}

您也可以使用 fill 构造函数来实现相同的东西。