[英]Splitting array into separate positive and negative arrays c++
我需要編寫一個函數,該函數接受給定的數組,然后將其拆分為兩個單獨的數組,其中一個數組的元素是主數組的正元素,另一個數組的元素是主數組的負元素。 我似乎無法弄清楚執行此操作的循環是什么樣的。
我編寫了一個單獨的函數來確定主數組中有多少個正值和負值:
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)
我只是不知道如何將主數組中的每個正數元素設置為新的“僅正數”數組中的元素,同樣將其設置為負數數組。
謝謝你的幫助!
使用給出的答案並盡力處理其余代碼后,嘗試編譯時出現了大約一百萬行錯誤。 我如何刪除三個動態分配的數組有問題嗎? 哪些巨大的錯誤正在阻止編譯? 這是我的代碼:
#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;
}
該代碼應該讀入數組並顯示新的負數組和正數組。 提前致謝!
您可能會得到一些C風格的答案
但是這里我將如何使用STL算法,因為這是為C++
標記的
bool is_pos(int i) { return i > 0; }
auto p = std::partition(std::begin(ARRAY),
std::end(ARRAY), std::ptr_fun(is_pos));
std::copy(std::begin(ARRAY), p, std::begin(POS_ARRAY));
std::copy(p, std::end(ARRAY), std::begin(NEG_ARRAY));
另外,您應該使用std::vector
進行此類操作
在這里演示
它很容易修改您的count()
函數:
void split(int ARRAY[], int SIZE, int NEG [], int POS [])
{
int ncount = 0, pcount = 0;
for (int x=0; x<SIZE; x++)
{
if(ARRAY[x]>=0)
{
POS[pcount++] = ARRAY[x];
}
if(ARRAY[x]<0)
{
NEG[ncount++] = ARRAY[x];
}
}
}
這段代碼會將負數和正數分成單獨的數組,
void split(int ARRAY[], int SIZE, int NEG_ARRAY[], int&NEG, int POS_ARRAY[], int&POS)
{
NEG=POS=0;
for (int i(0); i<SIZE; i++)
{
if (ARRAY[i]<0) NEG_ARRAY[NEG++]=ARRAY[i];
else POS_ARRAY[POS++]=ARRAY[i];
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.