如何根据参数的大小在函数内部声明数组? [英] How can I declare an array inside a function according to the size of a parameter?

查看:159
本文介绍了如何根据参数的大小在函数内部声明数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我尝试过的:

int fun1(vector<int> s)
{ 
    const int n = s.size();
    int arr[n]; //<----want to declare an array of length s.size()
}

但这告诉我n不是常数表达式,因此我不能用它来声明数组大小.但是,如果我尝试:

But this tells me that n is not a constant expression, so I cannot use it to declare the array size. But if I try:

int fun1(vector<int> s)
{ 
    const int n = 10;
    int arr[n]; //<-----this works
}

那很好.即使我将向量设置为const类型,它仍然不会将大小识别为常量表达式.我该怎么办?

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. How do I go about this?

推荐答案

必须在编译时确定大小为Nint arr[N];声明数组(某些编译器扩展允许您在运行时定义它们,时间也一样).顺便说一句,您可以做到:

Declaring array by 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). By the way, you can make it:

std::unique_ptr<int[]> arr (new int [n]);

// ... or ...

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

这篇关于如何根据参数的大小在函数内部声明数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆