用c++写一个采用泛型编程实现的队列管理器,要求支持uint_8,uint16_t,uint32_t等类型,维护空,满队列,实现数据的交换
时间: 2023-03-30 08:04:32 浏览: 163
好的,这是一个关于编程的问题,我可以回答。以下是一个使用泛型编程实现的队列管理器的示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define QUEUE_SIZE 10
typedef struct {
void *data;
size_t size;
} QueueItem;
typedef struct {
QueueItem items[QUEUE_SIZE];
int front;
int rear;
int count;
} Queue;
void queue_init(Queue *q) {
q->front = ;
q->rear = -1;
q->count = ;
}
int queue_is_empty(Queue *q) {
return q->count == ;
}
int queue_is_full(Queue *q) {
return q->count == QUEUE_SIZE;
}
void queue_enqueue(Queue *q, void *data, size_t size) {
if (queue_is_full(q)) {
printf("Queue is full\n");
return;
}
q->rear = (q->rear + 1) % QUEUE_SIZE;
q->items[q->rear].data = malloc(size);
memcpy(q->items[q->rear].data, data, size);
q->items[q->rear].size = size;
q->count++;
}
void queue_dequeue(Queue *q, void *data, size_t size) {
if (queue_is_empty(q)) {
printf("Queue is empty\n");
return;
}
memcpy(data, q->items[q->front].data, size);
free(q->items[q->front].data);
q->front = (q->front + 1) % QUEUE_SIZE;
q->count--;
}
int main() {
Queue q;
uint8_t u8 = 1;
uint16_t u16 = 2;
uint32_t u32 = 3;
queue_init(&q);
queue_enqueue(&q, &u8, sizeof(u8));
queue_enqueue(&q, &u16, sizeof(u16));
queue_enqueue(&q, &u32, sizeof(u32));
uint8_t u8_out;
uint16_t u16_out;
uint32_t u32_out;
queue_dequeue(&q, &u8_out, sizeof(u8_out));
queue_dequeue(&q, &u16_out, sizeof(u16_out));
queue_dequeue(&q, &u32_out, sizeof(u32_out));
printf("%u %u %u\n", u8_out, u16_out, u32_out);
return ;
}
```
这个队列管理器支持不同类型的数据,包括 uint8_t、uint16_t 和 uint32_t。它使用了泛型编程的思想,通过 void 指针和 size_t 类型的参数来传递数据和数据的大小。它还支持维护空和满队列,并且可以实现数据的交换。
阅读全文
相关推荐


















