c++ - 参数不能用作常数
问题描述
我刚刚完成了我的代码,我被最后两个错误困住了:“参数“n”的值不能用作常数。” 我在我的函数中使用“int n”来计算平均时间。
void findavgTime(int option, int pids[], int arrivals[], int n, int bursts[], int quanta) {
int resp[n], ta_time[n], avg_resp_time = 0, avg_ta_time = 0;
我该怎么办?
解决方案
在 C++ 中,数组的大小必须是编译时常数。所以你不能写这样的代码:
int n = 10;
int arr[n]; //incorrect
正确的写法是:
const int n = 10;
int arr[n]; //correct
出于同样的原因,您的代码中的以下代码也是不正确的:
int resp[n], ta_time[n];//incorrect because n must be a compile time constant
您可以将std::vector<>
其用于您的目的,而不是使用内置数组。std::vector
因此,您可以拥有/创建命名的数组,而不是创建数组resp
,ta_time
如下所示:
//n denotes the size. You can also use std::vector::reserve for requesting that the vector capacity be at least enough to contain n elements
std::vector<int> resp(n);
std::vector<int> ta_time(n);
推荐阅读
- typescript - TS2339:交替类型无法识别属性
- cassandra - 在 Windows 上启动 Cassandra 时出现致命的 Java 错误
- windows - 自删除 PowerShell 脚本会删除所有内容,但不会删除包含/父文件夹
- javascript - 包含隐藏元素的搜索
- python - 如何处理 jupyter-notebook 上的鼠标事件
- docker - 是否可以从 Dockerfile 创建 Singularity 映像?
- python - 将灰度图像转换为二进制时如何使用局部阈值?
- python - Python restframework 返回 ImportError: No module named but no syntax error
- r - 线性回归中的 R 稳健标准误差作为在 glht() 中使用的 lm 对象
- testing - 域错误测试和控制流/数据流测试有什么区别?