输出 [left]=input[i] 行中的 c++ 代码中存在无效的类型错误

Invalid type error in c++ code in output[left]=input[i] line

本文关键字:代码 存在 类型 错误 c++ 无效 left input 输出      更新时间:2023-10-16

我得到了这个

'invalid types int*[std::ios_based&(std::ios_base&)]' for array subscript  in line                   
output[left]=input[i];  

无法找出解决方案。 这里的输出是我想要答案的数组

#include <bits/stdc++.h>
using namespace std;
void recover(int input[], int output[], int n)
{
int i = 0;
int mid = n / 2;
if (n % 2 != 0)
{
output[mid] = input[i];
int left = mid - 1;
int right = mid + 1;
i++;
}
else
{
int left = mid - 1;
int right = mid;
}
while (i < n)
{
output[left] = input[i];
left--;
i++;
output[right] = input[i];
right++;
i++;
}
}
int main()
{
int input[100], output[100];
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> input[i];
}
recover(input, output, n) for (int i = 0; i < n; i++)
{
cout << output[i] << " ";
}
}

首先,正如Richard Critten在评论中指出的那样,您有一个范围问题。rightleftwhile循环中没有您在ifelse语句中给出的定义。

雪上加霜的是,您使用#include <bits/stdc++.h>using namespace std;.这些不会导致您的问题,但它们使问题更难理解。

使用#include <bits/stdc++.h>是一个坏主意。它包括整个C++标准库,这是懒惰的,不必要的,并且增加了编译时间。它也不是便携式的。

使用using namespace std;是一个坏主意。它使命名空间中的所有内容std无需限定即可使用。这意味着任何常用名称(如leftright(都可能与您不想要的内容匹配。这可能会导致非常难以找到和修复的错误。

同时使用两者真的很糟糕,因为现在你拥有了整个std命名空间,有很多常用名称,与你想要在代码中使用的名称发生冲突。