具有 2 个未知大小和 1 个已知大小的 3D 矢量

3D vector with 2 unknown sizes and 1 known size

我的程序接收 2 个维度作为命令行参数(M 为宽度,N 为高度)。只要 M 和 N 在 [3-10000] 之间,我就必须处理任何维度。

我想计算矩阵中的值(由 3D 向量表示),但我想保留以前的值来计算新值(这就是为什么一维只有 2 维:0=旧, 1=新).

这将给我一个类似于 matrix[M][N][2]matrix[2][M][N] 的结构。我没有偏好(哪个更简单,可能是后者)。

由于 M 和 N 仅在运行时已知,我不能使用简单的数组(我可以使用 double ***arr 但我不想弄乱内存分配)

我应该为 3 个维度中的每一个都使用一个向量,还是只为那些未知的维度使用向量?换句话说,我应该为 0=old、1=new 和 M 和 N 的向量使用一个简单的数组吗?

无论选择哪个,我都在努力让它发挥作用。如何创建和初始化它?

Should I use a vector for each of the 3 dimensions?

是的,你应该。

当标准库为您提供功能时,编写您自己的内存分配和释放代码没有任何优势。

Whichever is chosen, I am struggling to make it work, how do I create and initialize it?

假设您已经弄清楚如何从命令行获取 MN,您可以使用:

std::vector<int> d1(N, 0);
std::vector<std::vector<int>> d2(M, d1);
std::vector<std::vector<std::vector<int>>> matrix(2, d2);

您也可以将其合并为一行:

std::vector<std::vector<std::vector<int>>> matrix(2, std::vector<std::vector<int>>(M, std::vector<int>(N, 0)));

我更喜欢第一种方法。可以更轻松地了解正在执行的操作。

如果您只使用两个矩阵,我会使用长度为 2 的数组:

std::array<std::vector<std::vector<int>>, 2 > matrices{ {
    std::vector<std::vector<int>>(M, std::vector<int>(N, 0)),
    std::vector<std::vector<int>>(M, std::vector<int>(N, 0))
} };

用法:

int a=matrices[0][M][N];

虽然我认为您的程序会受益于某些类型别名。这是一个完整的例子:

#include <vector>
#include <array>
#include <iostream>

template<class T>
using Row = std::vector < T > ;

template<class T>
using Matrix = std::vector < Row<T> > ;

std::array<Matrix<int>, 2 > matrices;

int main()
{
    size_t M, N;
    int d;
    std::cin >> M;
    std::cin >> N;
    std::cin >> default;
    matrices.fill(Matrix<int>(M, Row<int>(N,d)));

    for (auto& r : matrices[0]){
        for (auto& e : r) {
            std::cout << e << " ";
        }
        std::cout << std::endl;
    }
    return 0;
}