7章作业: 设计一个只能容纳有限个元素的队列类,当队列满时添加元素就抛出一个队列满异常;当队列空时取出元素,就抛出一个队列空异常。编写程序并测试队列类。要求:使用动态数组存放队列元素。
时间: 2024-04-21 21:19:53 浏览: 17
7章作业是设计一个有限容量的队列类,具体要求如下:
1. 队列满时添加元素会抛出一个队列满异常。
2. 队列空时取出元素会抛出一个队列空异常。
3. 使用动态数组来存放队列元素。
4. 编写程序并测试队列类。
以下是一个可能的实现方式:
```cpp
#include <iostream>
#include <stdexcept>
class Queue {
private:
int* arr; // 动态数组
int capacity; // 队列容量
int front; // 队头指针
int rear; // 队尾指针
int size; // 当前队列大小
public:
Queue(int capacity) {
this->capacity = capacity;
arr = new int[capacity];
front = 0;
rear = -1;
size = 0;
}
~Queue() {
delete[] arr;
}
void enqueue(int element) {
if (isFull()) {
throw std::overflow_error("Queue is full");
}
rear = (rear + 1) % capacity;
arr[rear] = element;
size++;
}
int dequeue() {
if (isEmpty()) {
throw std::underflow_error("Queue is empty");
}
int element = arr[front];
front = (front + 1) % capacity;
size--;
return element;
}
bool isEmpty() {
return size == 0;
}
bool isFull() {
return size == capacity;
}
};
int main() {
Queue queue(5);
try {
queue.dequeue(); // 队列为空,抛出队列空异常
} catch (std::underflow_error& e) {
std::cout << "Exception caught: " << e.what() << std::endl;
}
try {
for (int i = 0; i < 6; i++) {
queue.enqueue(i); // 队列已满,抛出队列满异常
}
} catch (std::overflow_error& e) {
std::cout << "Exception caught: " << e.what() << std::endl;
}
for (int i = 0; i < 5; i++) {
try {
std::cout << queue.dequeue() << " "; // 依次取出队列元素
} catch (std::underflow_error& e) {
std::cout << "Exception caught: " << e.what() << std::endl;
}
}
return 0;
}
```