본문 바로가기
프로그래밍

[C++] 명품 c++ 프로그래밍 실습 6장 6번

by 엽기토기 2020. 12. 23.
반응형
#include <iostream>
#include <stdlib.h>
using namespace std;

class ArryUtility2 {
public:
	static int* concat(int s1[], int s2[], int size);
	static int* remove(int s1[], int s2[], int size, int& retSize);
};

//s1과 s2를 연결한 새로운 배열을 동적 생성하고 포인터 리턴
int* ArryUtility2::concat(int s1[], int s2[], int size) {
	int *result = new int[size * 2];
	for (int i = 0; i < size; i++) {
		result[i] = s1[i];
		result[i + size] = s2[i];
	}
	return result;
}

//s1에서 s2에 있는 숫자를 모두 삭제한 새로운 배열을 동적 생성하여 리턴,
//리턴하는 배열의 크기는 retsize에 전달. retsize가 0인 경우 NULL 리턴
int* ArryUtility2::remove(int s1[], int s2[], int size, int& retSize) {//call by reference
	int a = 0, b = 0; //a는 같은 원소 개수 세는거

	for (int i = 0; i < size; i++) {
		for (int j = 0; j < size; j++) {
			if (s1[i] == s2[j]) {
				a++;
				s1[i] = NULL;
			}
		}
	}
	retSize = size - a; //동일 원소 개수 뺌

	int *result = new int[retSize];
	for (int i = 0; i < size; i++) {
		if (s1[i] != NULL) {
			result[b] = s1[i];
			b++;
		}
	}
	if (retSize == 0) return NULL;
	else return result;
}

int main() {
	int x[5], y[5], *concresult = NULL, *remvresult = NULL, num;

	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];

	concresult = ArryUtility2::concat(x, y, 5);
	cout << "합친 정수 배열을 출력한다 \\n";
	for (int i = 0; i < 10; i++) {
		cout << concresult[i] << ' ';
	}
	cout << endl;

	remvresult = ArryUtility2::remove(x, y, 5, num);
	cout << "배열 x[]에서 y[]를 뺀 결과를 출력한다. 개수는 " << num << endl;
	for (int i = 0; i < num; i++) {
		cout << remvresult[i] << ' ';
	}
	cout << endl;

}
반응형