명품C++프로그래밍
명품 C++ Programming 실습문제 8장 5번
anycoding
2021. 5. 22. 01:25
반응형
문제 5, 6번에 적용되는 BaseArray 클래스는 다음과 같다.
class BaseArray {
private:
int capacity; // 배열의 크기
int* mem; // 정수 배열을 만들기 위한 메모리의 포인터
protected:
BaseArray(int capacity = 100)
{
this->capacity = capacity; mem = new int[capacity];
}
~BaseArray() { delete[]mem; }
void put(int index, int val) { mem[index] = val; }
int get(int index) { return mem[index]; }
int getCapacity() { return capacity; }
};
문제
BaseArray를 상속받아 큐처럼 작동하는 MyQueue클래스를 작성하라. MyQueue를 활용하는 사례는 다음과 같다.
int main()
{
MyQueue mQ(100);
int n;
cout << "큐에 삽입할 5개의 정수를 입력하라>> ";
for (int i = 0; i < 5; i++)
{
cin >> n;
mQ.enqueue(n); //큐에 삽입
}
cout << "큐의 용량 : " << mQ.capacity() << ", 큐의 크기 : " << mQ.length() << endl;
cout << "큐의 원소를 순서대로 제거하여 출력한다>> ";
while (mQ.length() != 0) {
cout << mQ.dequeue() << ' '; //큐에서 제거하여 출력
}
cout << endl << "큐의 현재 크기 : " << mQ.length() << endl;
}
결과
큐에 삽입할 5개의 정수를 입력하라>> 1 3 5 7 9
큐의 용량:100, 큐의 크기:5
큐의 원소를 순서대로 제거하여 출력한다>> 1 3 5 7 9
큐의 현재 크기 : 0
소스코드
#include<iostream>
using namespace std;
class BaseArray {
private:
int capacity; // 배열의 크기
int* mem; // 정수 배열을 만들기 위한 메모리의 포인터
protected:
BaseArray(int capacity = 100)
{
this->capacity = capacity; mem = new int[capacity];
}
~BaseArray() { delete[]mem; }
void put(int index, int val) { mem[index] = val; }
int get(int index) { return mem[index]; }
int getCapacity() { return capacity; }
};
class MyQueue : public BaseArray {
int front, rear;
public:
MyQueue(int capacity) : BaseArray(capacity) { front = 0; rear = 0; }
void enqueue(int data);
int dequeue();
int capacity();
int length();
};
void MyQueue::enqueue(int data)
{
if (rear >= getCapacity()) {
cout << "큐가 가득찼습니다." << endl;
exit(1);
}
put(++rear, data);
}
int MyQueue::dequeue()
{
if (front == rear) {
cout << "꺼낼 데이터가 없습니다." << endl;
exit(1);
}
--rear;
return get(++front);
}
int MyQueue::capacity()
{
return getCapacity();
}
int MyQueue::length()
{
return rear;
}
int main()
{
MyQueue mQ(100);
int n;
cout << "큐에 삽입할 5개의 정수를 입력하라>> ";
for (int i = 0; i < 5; i++)
{
cin >> n;
mQ.enqueue(n); //큐에 삽입
}
cout << "큐의 용량 : " << mQ.capacity() << ", 큐의 크기 : " << mQ.length() << endl;
cout << "큐의 원소를 순서대로 제거하여 출력한다>> ";
while (mQ.length() != 0) {
cout << mQ.dequeue() << ' '; //큐에서 제거하여 출력
}
cout << endl << "큐의 현재 크기 : " << mQ.length() << endl;
}
반응형