仿写队列类queue
时间: 2023-08-03 20:20:21 浏览: 53
好的,以下是一个简单的仿写STL队列类queue的示例代码:
```c++
#include <iostream>
#include <stdexcept>
using namespace std;
template<typename T>
class myQueue {
private:
T *arr;
int size, capacity;
int frontIndex, backIndex;
public:
myQueue(int capacity = 10) {
arr = new T[capacity];
size = 0;
this->capacity = capacity;
frontIndex = backIndex = 0;
}
~myQueue() {
delete[] arr;
}
bool empty() const {
return size == 0;
}
int getSize() const {
return size;
}
void push(T val) {
if (size == capacity) {
throw out_of_range("queue is full");
}
arr[backIndex] = val;
backIndex = (backIndex + 1) % capacity;
size++;
}
void pop() {
if (empty()) {
throw out_of_range("queue is empty");
}
frontIndex = (frontIndex + 1) % capacity;
size--;
}
T front() const {
if (empty()) {
throw out_of_range("queue is empty");
}
return arr[frontIndex];
}
T back() const {
if (empty()) {
throw out_of_range("queue is empty");
}
return arr[(backIndex - 1 + capacity) % capacity];
}
};
int main() {
myQueue<int> q;
for (int i = 1; i <= 5; i++) {
q.push(i);
}
cout << "front: " << q.front() << endl;
cout << "back: " << q.back() << endl;
while (!q.empty()) {
cout << q.front() << " ";
q.pop();
}
cout << endl;
return 0;
}
```
这个队列使用了数组实现,其中frontIndex指向队列头部的元素,backIndex指向队列尾部的下一个元素。在插入元素时,我们只需要将元素插入到backIndex位置即可。在弹出元素时,我们只需要将frontIndex加1即可。需要注意的是,我们使用取模运算来实现backIndex的循环。在计算backIndex时,我们需要使用(backIndex - 1 + capacity) % capacity来避免backIndex超出数组的范围。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)