c++ - 为什么会出现“多个测试用例”错误?
问题描述
我已经编写了用于消除数组中最大 2 个元素的代码,但是这段代码给出了testcase > 1
. 为什么?
输入:
no of TestCase
size of array
elements of array
排序功能:
int sort_asc(int arr[], int n)
{
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(arr[j]<arr[i])
{
int temp;
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
}
int main() {
//code
int test;
cin>>test;
while(test--){
//taking size and array as inputs
int size;
cin>>size;
int a[size];
cin>>a[size];
for(int i=0;i<size;i++){
cin>>a[i];
}
//sorting the array
sort_asc(a,size);
//printing the output discarding last 2 elements of the array
for(int i=0;i<size-2;i++){
cout<<a[i]<<" ";
}
cout<<"\n";
}
return 0;
}
预期的:
12 23 28 43 44 59 60 68 70 85 88 92 124 125 136 168 171 173 179 199 212
230 277 282 306 314 316 325 328 336 337 363 365 368 369 371 374 387 394 414
422 427 430 435 457 493 506 527 531 538 541 546 568 583 650 691 730 737 751
764 778 783 785 789 794 803 809 815 847 858 863 874 887 896 916 920 926 927 930 957
我的输出:
12 23 28 43 44 59 60 68 70 81 85 88 92 124 125 136 168 171 173 179 199 212 230 277 282 306 314 316 325 328 336 337 363 365 368 369 371 374 387 394 414 422 427 430 435 457 493 506 527 531 538 541 546 568 583 650 691 730 737 751 764 778 783 785 789 794 803 809 815 847 858 863 874 887 896 916 920 926 930 957
解决方案
VLA(可变长度数组)是无效的 C++ 代码。一些编译器可以容忍它,但它仍然无效。
但这不是你的主要问题。您产生了超出范围的错误。数组索引从 0 开始。最后一个元素的位置为 size-1。所以你的陈述
cin>>a[size];
将写到数组的末尾。产生未定义的行为。
我不确定你为什么要发表声明,但在那之后,任何未定义的事情都可能而且很可能会发生。
推荐阅读
- c# - 如何将字符串列表绑定到 ASP.NET MVC 中的 datalist id?
- c - 对象宏的最大尺寸
- r - 有没有比“for”循环更有效的方法来填充额外的列?
- c - 如何从高架摄像头考虑建筑轨迹中像素的旋转?
- php - 在 foreach 循环中努力评估 if 语句
- tensorflow - 在缺少操作的情况下扩展 TF Lite GPU 委托
- java - MessageQueue 回调中的异常:handleReceiveCallback 洪水填充算法 Android
- javascript - 通过预处理更改元素 ID 和类
- html - 如何修复 TypeError:无法读取未定义的属性“修剪”
- python - 我需要在矩形中添加文本,我该怎么做?