c++ - 如何根据参数的大小在函数内声明一个数组?

标签 c++ arrays vector

这是我尝试过的:

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/

相关文章:

c++ - 使用额外的模板类型参数作为类型别名声明以在函数的签名中使用

c++ - 为什么 setwidth 为其他值 1 会使我的线消失?

python - 在构建 python/cython 扩展时指定替代链接器?

c - 静态字符数组的含义?

c++ - 在 C++ 中打印集合 vector

c++ - 返回 std::vector - 正确的方法

c++ - 在 C++ DLL 实例之间共享对象

PHP获取数组值和数组键

java - 找出可能的最大总和

c++ - 面向对象框架中成员函数返回std::vector.size()的效率