我正在使用 visual studio 2013 express 和 MSVC 编译器。
我在执行以下代码行时遇到错误。
#include<iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int a[n];
return 0;
}
它说在我声明数组 a
的那一行表达式必须有一个常量值。
我搜索并找到了这个 c++ array - expression must have a constant value
它说你需要打开一个编译器选项来允许它。 如何在 Visual Studio Express 中设置该选项?
最佳答案
你可以使用指针
int*a = new int [n];
你必须在离开你的a
范围之前删除:
delete[] a;
但最好使用 vector :
vector<int> a(n);
您还可以使用 llvm smallvector,它针对没有堆分配的小型数组进行了优化,如果大小很小的话
llvm::SmallVector<int, 5> smallVector;
for(int i = 0; i < 5; i++) {
smallVector.push_back(i); } // No heap allocations have been performed up to this point.
smallVector.push_back(6); // heap allocation now
但请记住,编译器将决定在哪里分配。 Smallvector
关于c++ - 使用 MSVC C++ 编译器创建动态大小的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56555406/