特定の配列を取り、それを 2 つの別個の配列に分割する関数を作成する必要があります。一方の配列の要素はメイン配列の正の要素であり、もう一方の要素はメイン配列の負の要素です。これを行うためのループがどのようになるかわかりません。
メイン配列に正と負の値がいくつあるかを判断する別の関数を作成しました。
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)
メイン配列の各正の要素を新しいPositive-Only配列の要素として設定する方法、および負の配列についても同様に設定する方法がわかりません。
ご協力いただきありがとうございます!
与えられた答えを使用し、残りのコードで最善を尽くした後、コンパイルしようとすると約100万行のエラーが発生しました. 動的に割り当てられた 3 つの配列を削除する方法に問題はありますか? コンパイルを妨げている大きなエラーは何ですか? これが私のコードです:
#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;
}
このコードは、配列を読み取り、新しい負の配列と正の配列を表示することになっています。前もって感謝します!