c++ - 通过传递其长度在函数内部声明一个数组
问题描述
我想要一个函数,它接受一个正整数,然后声明一个数组,初始化它并打印它。以下代码适用于 GCC 编译器,但不适用于 MSVC 编译器。我得到错误
错误(活动) E0028 表达式必须有一个常数值。参数“Length”的值(在第 5 行声明)不能用作常量
- 使用 MSVC 编译器执行此操作的好方法是什么?和
- 这种差异有什么好的理由吗?
我的代码:
#include <iostream>
using namespace std;
void Print(const int Length)
{
int Array[Length];
for (int i = 0; i <= Length - 1; i++)
{
Array[i] = i;
cout << Array[i];
}
}
int main()
{
const int L = 5;
Print(L);
return 0;
}
解决方案
如果您真的想要一个动态分配的、固定大小的数组,请使用 std::unique_ptr 而不是 std::vector。
#include <iostream>
#include <memory>
void Print(const int Length){
std::unique_ptr<int[]> Array = std::make_unique<int[]>(Length);
for (int i = 0; i < Length; ++i){
Array[i] = i;
std::cout << Array[i];
}
Array.reset();
}
推荐阅读
- python - 我的代码在功能上没问题,但我想尽量减少代码行。有没有办法在两行或更少的代码中制作以下代码?
- django - 在 ModelForm 字段中使用 self
- php - 使用 UNION 获取日期范围之间的 SUM
- xml - 如何在 SQL Server 2016 中向 XML 添加带有编码的 XML 声明序言?
- python - 递归阶乘函数的代码,将用户输入放入 np 数组并打印它们的阶乘
- awk - 使用 sed/grep 在标签前添加/插入代码
- laravel - Laravel 自定义验证器
- regex - 使用正则表达式获取前面不包含特定单词的句子中的特定字符串?
- javascript - URI Malformed Error Javascript Google 也有这个问题?
- azure-devops - 将输出添加到 Azure Devops 管道作业摘要屏幕