[英]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
我没有在 stackoverflow 中找到这个问题的答案。(现有问题似乎没有解决我的问题......)
如何在 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 的容量大于它的大小,我想避免这种情况。 但另一个问题: How to limit the capacity of std::vector to the number of element show 我应该使用我的分配器或std::vector::shrink_to_fit()
来避免它......(在 C++ 中没有保证17 如果你使用reserve(n)
)
C++ 中动态分配的数组容器是std::vector
。 std::array
专门用于编译时定长数组。
https://cppreference.com是你的朋友!
但是vector内存大小需要自己整理
不太确定你的意思,但是你使用构造函数指定了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
更具优势的原因。
有关如何实现该要求的技术解释,请记住模板参数必须是编译时常量(因为它会改变代码的生成方式,同样是在编译时)。
无论如何,您想在这里使用std::vector
。 如果您知道所需的大小,请将其作为构造函数参数提供。
对于所有感到困惑的人,他只是问他想要一个固定的二维数组,其大小在运行时确定
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.