采用泛型编程设计一个队列管理器,要求支持uint8_t,uint16_t,uint32_t等类型,维护空、满队列,实现数据的交换
时间: 2023-12-01 15:03:56 浏览: 81
```c++
#include <iostream>
#include <queue>
template <typename T>
class QueueManager {
private:
std::queue<T> q;
const int MAX_SIZE;
public:
QueueManager(int max_size) : MAX_SIZE(max_size) {}
bool isFull() const {
return q.size() == MAX_SIZE;
}
bool isEmpty() const {
return q.empty();
}
bool enqueue(const T& data) {
if (isFull()) {
return false;
}
q.push(data);
return true;
}
bool dequeue(T& data) {
if (isEmpty()) {
return false;
}
data = q.front();
q.pop();
return true;
}
bool swap(QueueManager<T>& other) {
if (this == &other) {
return true;
}
if (isFull() || other.isFull()) {
return false;
}
while (!isEmpty() && !other.isFull()) {
T data;
dequeue(data);
other.enqueue(data);
}
return true;
}
};
int main() {
QueueManager<uint8_t> q1(5);
QueueManager<uint16_t> q2(5);
QueueManager<uint32_t> q3(5);
for (int i = 0; i < 5; i++) {
q1.enqueue(i);
q2.enqueue(i * 10);
q3.enqueue(i * 100);
}
std::cout << "q1 is full: " << q1.isFull() << std::endl;
std::cout << "q2 is full: " << q2.isFull() << std::endl;
std::cout << "q3 is full: " << q3.isFull() << std::endl;
uint8_t data1;
uint16_t data2;
uint32_t data3;
while (!q1.isEmpty() && !q2.isFull()) {
q1.dequeue(data1);
q2.enqueue(data1 * 100);
}
while (!q2.isEmpty() && !q3.isFull()) {
q2.dequeue(data2);
q3.enqueue(data2 * 1000);
}
std::cout << "q1 is empty: " << q1.isEmpty() << std::endl;
std::cout << "q2 is empty: " << q2.isEmpty() << std::endl;
std::cout << "q3 is empty: " << q3.isEmpty() << std::endl;
q1.swap(q2);
std::cout << "q1 is empty: " << q1.isEmpty() << std::endl;
std::cout << "q2 is empty: " << q2.isEmpty() << std::endl;
std::cout << "q3 is empty: " << q3.isEmpty() << std::endl;
return 0;
}
```
阅读全文