[英]How can I declare an array inside a function according to the size of a parameter?
Here is what I have tried: 这是我尝试过的:
int fun1(vector<int> s)
{
const int n = s.size();
int arr[n]; //<----want to declare an array of length s.size()
}
But this tells me that n is not a constant expression, so I cannot use it to declare the array size. 但这告诉我n不是常数表达式,所以我不能用它来声明数组大小。 But if I try:
但是,如果我尝试:
int fun1(vector<int> s)
{
const int n = 10;
int arr[n]; //<-----this works
}
then it's fine. 那很好 Even if I make the vector s of type const, it still won't recognize the size as a constant expression.
即使我将向量设置为const类型,它仍然不会将大小识别为常量表达式。 How do I go about this?
我该怎么办?
Declaring array by int arr[N];
通过
int arr[N];
声明数组int arr[N];
the size N
must be determined in compile-time (except for some compiler extensions which allow you to define them in run-time too). 大小
N
必须在编译时确定(某些编译器扩展除外,它们也允许您在运行时定义它们)。 By the way, you can make it: 顺便说一句,您可以做到:
std::unique_ptr<int[]> arr (new int [n]);
// ... or ...
std::vector<int> arr(n);
When you declare an array like this 当你这样声明一个数组
int arr[n];
the compiler will allocate memory on the stack for it. 编译器将在堆栈上为其分配内存。 In this case the C++ standard requires that
n
is known at compile time, ie it must be const
. 在这种情况下,C ++标准要求
n
在编译时是已知的,即它必须是const
。
The answer to your question is to get the memory from the heap at run time like this: 您问题的答案是像这样在运行时从堆中获取内存:
int* arr = new int[n];
In this case the memory is allocated at run time and so the value of n
doesn't need to be known until run time. 在这种情况下,内存是在运行时分配的,因此直到运行时才需要知道
n
的值。 If you use this approach don't forget to free up the memory when you're done with: 如果使用这种方法,请别忘了在完成以下操作后释放内存:
delete [] arr;
However, as the comments suggest, using a std::vector<int>
would almost certainly be a better approach. 但是,正如评论所建议的那样,使用
std::vector<int>
几乎可以肯定是一种更好的方法。 Unless you've got a good reason not to, I'd go with that. 除非您有充分的理由不这样做,否则我会同意的。
For this, C++ has std::vector<int>(n)
, which retains most of the semantics of a traditional C array but also adds a lot of benefits (dynamic allocation being one, resizing is another, algorithm support is yet another one). 为此,C ++具有
std::vector<int>(n)
,它保留了传统C数组的大部分语义,但也带来了很多好处(动态分配是一种,调整大小是另一种,算法支持是另一种) )。 Even when your underlying code requires a C array, you can still use the vector and pass an address of the first element down (they are guaranteed to be contiguous). 即使您的基础代码需要C数组,您仍然可以使用该向量并向下传递第一个元素的地址(保证它们是连续的)。
Typically, std::vector
uses heap for underlying storage, so on one hand you are better protected from stack overflows (pun intended), on the other hand, your code now uses dynamic allocation. 通常,
std::vector
使用堆作为基础存储,因此一方面可以更好地保护其免受堆栈溢出(双关语)的影响,另一方面,您的代码现在使用动态分配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.