我需要编写一个程序,它接受一个给定的数组,然后将它分成两个单独的数组,一个数组的元素是主数组的正元素,另一个数组的元素是主数组的负元素。
在尽我最大努力编写代码后,我在尝试编译它时遇到了大约一百万行错误。我如何删除三个动态分配的数组有问题吗?阻止编译的巨大错误是什么? 这是我的代码:
#include <iostream>
using namespace std;
void count(int ARRAY[], int SIZE, int& NEG, int& POS);
void split(int ARRAY[], int SIZE, int& NEG_ARRAY, int NEG, int& POS_ARRAY, int POS);
void print_array(int ARRAY[], int SIZE);
int main()
{
int SIZE(0);
int* ARRAY;
cout << "Enter number of elements: ";
cin >> SIZE ;
ARRAY = new int[SIZE];
int x(0);
int numEle(0);
cout << "Enter list: " << endl;
while (numEle < SIZE)
{
ARRAY[numEle] = x;
numEle++;
cin >> x;
}
int POS(0), NEG(0);
count(ARRAY, SIZE, NEG, POS);
int* NEG_ARRAY;
NEG_ARRAY = new int[NEG];
int* POS_ARRAY;
POS_ARRAY = new int[POS];
split(ARRAY, SIZE, NEG_ARRAY, NEG, POS_ARRAY, POS);
cout << "Negative elements: " << endl;
cout << print_array(NEG_ARRAY, NEG) << endl;
cout << "Non-negative elements: " << endl;
cout << print_array(POS_ARRAY, POS) << endl;
delete [] ARRAY;
delete [] NEG_ARRAY;
delete [] POS_ARRAY;
return 0;
}
void count(int ARRAY[], int SIZE, int& NEG, int& POS)
{
for (int x=0; x < SIZE; x++)
{
if (ARRAY[x] >= 0)
{
POS = POS + 1;
}
if (ARRAY[x] < 0)
{
NEG = NEG + 1;
}
}
}
void split(int ARRAY[], int SIZE, int& NEG_ARRAY, int NEG, int& POS_ARRAY, int POS)
{
NEG = POS = 0;
for (int x = 0; x < SIZE; x++)
{
if (ARRAY[x] < 0)
{
NEG_ARRAY[NEG++] = ARRAY[x];
}
else
{
POS_ARRAY[POS++] = ARRAY[x];
}
}
}
void print_array(int ARRAY[], int SIZE)
{
for (int i = 0; i < SIZE; i++)
{
cout << ARRAY[i] << " ";
}
cout << endl;
}
代码应该读入数组并显示一个新的负数组和一个新的正数组。提前致谢!
最佳答案
您的代码中有一堆错误。最糟糕的是在 split
函数的声明和定义中通过引用传递数组。将两者都更改为 void split(int ARRAY[], int SIZE, int *NEG_ARRAY, int NEG, int *POS_ARRAY, int POS);
,大部分错误都会消失。
其余部分来自您在 main
中打印数组的两行:
cout<<print_array(NEG_ARRAY, NEG) <<endl;
您不想打印该函数,而是想使用该函数在其中打印(您做对了)。您需要将调用更改为:
print_array(NEG_ARRAY, NEG);
这将使您的代码编译通过。
但是还有一个错误,这将使整个应用程序以不正确的方式工作。在您输入值的地方,您需要从 cin
获取输入,然后再将其输入到数组中。像这样:
while(numEle<SIZE) {
cin>>x;
ARRAY[numEle] = x ;
numEle++;
}
关于C++将一个数组拆分为2个单独的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19993256/