2-8 school exercise exploded array in accordance with the positive and negative

topic:

Try to write a function, the integer n has a non-zero elements one-dimensional array A [n] is split into two one-dimensional array, such that A [] is greater than zero is stored in the element B [], less than zero elements located in the C [] in.

Array.h

#pragma once
#include<iostream>
using namespace std;

class Array {
    int* data;
    int num; //num<=>lenth
    int maxSize;
public:
    Array(int size) {
        maxSize = size;
        data = new int[maxSize];
        num = 0;
    }
    void creat(int* arr,int  n) {
        for (int i = 0; i < n; i++) {
            data[i] = arr[i];
            num++;
        }
    }
    void show() {
        for (int i = 0; i < num; i++) {
            cout << data[i] << " ";
        }
        cout << endl;
    }
    void divide(Array& B, Array& C) {
        B.num = 0;
        C.num = 0;
        for (int i = 0; i < num; i++) {
            if (data[i] > 0) {
                B.data[B.num++] = data[i];
            }
            else if (data[i] < 0) {
                C.data[C.num++] = data[i];
            }
        }
    }
};

main.cpp

#include"Array.h"

int main() {
    Array A(9);
    Array B(9);
    Array C(9);
    int arr[] = { -1,-8,6,4,-7,-3 };
    A.creat(arr, 6);
    A.show();
    A.divide(B, C);
    B.show();
    C.show();
    return  0;
}

 

Guess you like

Origin www.cnblogs.com/SlowIsFast/p/12501963.html