如何在 C++ 中动态分配 2D std::array 或者为什么我不应该使用它?

How to dynamically allocate a 2D std::array in C++ or why I should not use it?

我想在我的代码中 malloc 一个数组,它的大小应该在运行时定义。

我这样试过:

#include <iostream>
#include <array>

int main(){
    int M=4,N=3,P=5;
    M=N+P;
    std::array<std::array<double,M>,N> arr;
}

但是 MSVC 告诉我:

a variable with non-static storage duration cannot be used as a non-type argument

我在Whosebug中没有找到这个问题的答案。(现有的问题似乎没有解决我的问题...)

如何在 C++ 中动态分配 2D std::array?

我知道我可以使用 std::vector 来解决这个问题。但是向量内存大小需要自己整理,这个在我的项目中会用到很多次。而且我想使用 C++ 类型代码而不是 C 类型...也许有一种方法可以将 C 类型的二维数组转换为 std::array,但我无法通过 Google 找到它。 .

所以我问这个问题...

我的意思是M和N应该是动态获取的(没有改变,但我只能在运行时知道它......),如:

#include <iostream>

int main(){
    int a=3;
    int b=4;
    int rowCount=a+b;
    int colCout=b-a;
    int** a = new int*[rowCount];
    for(int i = 0; i < rowCount; ++i)
    {
        a[i] = new int[colCount];
    }
}

我知道我错在哪里了。我陷入了一个逻辑问题......如果我不使用push_back,向量效果很好。如果我使用它,数组也不起作用。

我认为 vector 的容量大于它的大小,我想避免这种情况。但另一个问题: show I show I should use my allocator or std::vector::shrink_to_fit() to avoid it...(如果使用 reserve(n),C++17 无法保证)

C++中动态分配的数组容器是std::vectorstd::array 专门用于 compile-time fixed-length 数组。

https://cppreference.com是你的朋友!

But the vector memory size needs to be organized by myself

不太确定你的意思,但是你使用构造函数指定了 std::vector 的大小。

std::vector<std::vector<int>> arr(N);

如果你需要一些特殊的分配器(不仅仅是new/malloc),那么你也可以指定一个自定义分配器。

你提出的整个程序都不是好的 C++。 C++ 解决方案如下所示:

#include <vector>
int main() {
    int a = 3;
    int b = 4;
    unsigned int rowCount = a + b;
    unsigned int colCount = b - a;
    std::vector<std::vector<int>> matrix(rowCount);
    for (auto& row : matrix) {
        row.resize(colCount);
    }
}

std::array,就像 C++ 中的实际数组一样,需要恒定大小。这就是它比 std::vector.

更具优势的原因

有关如何实现该要求的技术解释,请记住模板参数必须是 compile-time 常量(因为它改变了代码的生成方式,同样在 compile-time)。

无论如何,你想在这里使用std::vector。如果您知道所需的大小,请将其作为构造函数参数提供。