C++

명품 C++ 6장 6번

NUMERO_K 2018. 11. 2. 17:51

6. 동일한 크기의 배열을 변환하는 다음 2개의 static 멤버 함수를 가진 ArrayUtility2 클래스를 만들고, 이 클래스를 이용하여 아래 결과와 같이 출력되록 프로그램을 완성하라.


소스코드


#include <iostream>
using namespace std;
class ArrayUtility2 {
public:
    // s1과 s2를 연결한 새로운 배열을 동적 생성하고 포인터 리턴
    static int* concat(int s1[], int s2[], int size);
    // s1에서 s2에 있는 숫자를 모두 삭제한 새로운 배열을 동적 생성하여 리턴. 리턴하는 배열의 크기는
    // retSize에 전달. retSize가 0인 경우 NULL 리턴
    static int* remove(int s1[], int s2[], int size, int & resSize);
};
int* ArrayUtility2::concat(int s1[], int s2[], int size) {
    int *a=new int[size*2];
    for (int i = 0; i < size; ++i)
        a[i] = s1[i];
    for (int i = 0; i < size; ++i)
        a[i+size] = s2[i];
    return a;
}
int* ArrayUtility2::remove(int s1[], int s2[], int size, int & resSize) {
    int *b = new int[size];
    resSize = size;
    bool sw;
    for (int i = 0; i < size; ++i) {
        sw = false;
        for (int j = 0; j < size; ++j) {
            if (s1[i] == s2[j]) {
                sw = true;
                --resSize;
                break;
            }
        }
        if (!sw) b[i] = s1[i];
    }
    return b;
}
int main(){
    int x[5], y[5], *z;
    int retSize;
    cout << "정수를 5 개 입력하라 . 배열 x에 삽입한다>>";
    for (int i = 0; i < 5; ++i)
        cin >> x[i];
    cout << "정수를 5 개 입력하라 . 배열 y에 삽입한다>>";
    for (int i = 0; i < 5; ++i)
        cin >> y[i];
    z=ArrayUtility2::concat(x, y, 5);
    cout << "합친 정수 배열을 출력한다." << endl;
    for (int i = 0; i < 10; ++i)
        cout << z[i] << ' ';
    cout << endl;
    z = ArrayUtility2::remove(x, y, 5, retSize);
    cout << "배열 x[]에서 y[]를 뺀 결과를 출력한다. 개수는 2" << endl;
    for (int i = 0; i < retSize; ++i)
        cout << z[i] << ' ';
    cout << endl;
}


실행결과



concat 로 합친 배열을 z에 리턴합니다.


remove로  값을 제건한 배열을 z에 리턴합니다.


전역함수의 캡슐화를 위해 static 을 사용하여 클래스의 멤버 함수로 만듭니다.