基于数组的循环队列(C++模板实现)
2023-09-27 14:25:59 时间
循环队列使用数组实现的话,简单、方便。之前实现的队列,当尾端索引到达队列最后的时候,无论前面是否还有空间,都不能再添加数据了。循环队列使得队列的存储单元可以循环利用,它需要一个额外的存储单元来判断队列是否已满。
#pragma once #ifndef MSGQUEUE_H_ #define MSGQUEUE_H_ #include "SerialApi.h" #include <queue> #include <iostream> using namespace std; template<typename T> class MsgQueue{ public: MsgQueue(size_t sz); //构造 ~MsgQueue(); public: bool isEmpty(); //判断队列是否为空 bool isFull(); //判断队列是否为满 void Push(T &val); //入队操作 T Pop(); //出队操作 T getFront(); T getRear(); size_t getRealSize(); private: size_t front,rear,size; T *data; }; template<typename T> MsgQueue<T>::MsgQueue(size_t sz) { rear = front = 0; size = sz + 1; data = new T[size]; } template<typename T> MsgQueue<T>::~MsgQueue() { delete []data; } template<typename T> bool MsgQueue<T>::isEmpty() { return (front == rear); } template<typename T> bool MsgQueue<T>::isFull() { return (((rear+1) % size) == front); } template<typename T> void MsgQueue<T>::Push(T &val) { if(!isFull()) { data[rear] = val; rear = (rear + 1) % size; } else { printf("The queue is full!\n"); } } template<typename T> T MsgQueue<T>::Pop(void ) { T temp; if(!isEmpty()) { temp = data[front]; data[front] = NULL; front = (front+1) % size; return data[temp]; } else { printf("The queue is empty!\n"); return ; } } template<typename T> T MsgQueue<T>::getFront() { if(isEmpty()) { printf("The queue is empty!\n"); } return data[front]; } template<typename T> T MsgQueue<T>::getRear() { return data[rear]; } template<typename T> size_t MsgQueue<T>::getRealSize() { size_t realSize = (rear - front + size) % size; return realSize; } #endif //MSGQUEUE_H_
MsgQueue<int> *Q = new MsgQueue<int>(20); for(int i=0;i<20;i++) { Q->Push(i); } cout<<Q->getFront()<<endl; cout<<Q->getRealSize()<<endl;
参考链接:http://www.cnblogs.com/wxxweb/archive/2011/05/26/2059166.html
注意:模板声明和实现要放在同一文件夹中,而不能够把声明放在了.h文件中,把实现放在了.cpp文件中。
相关文章
- C/C++数据结构(三) —— 双向带头循环链表
- 【C/C++】让你对预处理更加了解!
- C++中的引用处理
- 【C++保姆级入门】习题掌握循环结构
- 【VS开发】【C++开发】正确使用auto_ptr智能指针
- C++-容器-string:数字to字符串【std::to_string()】、字符串to数字【std::stoi、stol、stoll、stoul、stoull、stof、stod、stold】
- 清华大学C++课程学习笔记——第三章函数
- c++笔记1
- C# 调用C++ SDK/API的问题总结
- How to mix C and C++
- Visual C++串口通信开发入门与编程实践
- 传智播客 C/C++学习笔记 野指针
- [C/C++]_[Unicode转Utf8,Ansi转Unicode,Ansi文件转Utf8文件]
- 用汇编的眼光看C++(之缺省模板、特化模板)
- (Windbg调试六)c++句柄泄漏问题定位
- Fixed width integer types (since C++11)
- 【温故而知新】C和C++10:关于const限定符