这是我尝试过的:
int fun1(vector<int> s)
{
const int n = s.size();
int arr[n]; //<----want to declare an array of length s.size()
}
但这告诉我 n 不是常量表达式,所以我不能用它来声明数组大小。但如果我尝试:
int fun1(vector<int> s)
{
const int n = 10;
int arr[n]; //<-----this works
}
那就没问题了。即使我将 vector 设为 const 类型,它仍然不会将大小识别为常量表达式。我该怎么做?
最佳答案
通过 int arr[N];
声明数组 N
的大小必须在编译时确定(除了一些允许您在运行时定义它们的编译器扩展-时间也是)。顺便说一句,你可以做到:
std::unique_ptr<int[]> arr (new int [n]);
// ... or ...
std::vector<int> arr(n);
关于c++ - 如何根据参数的大小在函数内声明一个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19527562/