这篇文章主要介绍C++中Queue队列类模版的示例分析,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
队列的定义
队列(Queue)是一种线性存储结构。它有以下几个特点:
按照"先进先出(FIFO, First-In-First-Out)"方式进出队列。
队列只允许在"队首"进行取出操作(出队列),在"队尾"进行插入操作(入队列 )
队列实现的方式有两种
基于动态数组实现
基于链表形式实现
队列需要实现的函数
T dequeue() :
出队列,并返回取出的元素
void enqueue(const T &t) :
入队列
T &head() :
获取队首数据,但是不会被取出
const T &head() const :
获取const类型队首数据
int length() const:
获取数量(父类已经实现)
void clear():
清空队列(父类已经实现)
本章,我们实现的队列基于链表形式实现,它的父类是我们之前实现的LinkedList类:
C++ 双向循环链表类模版实例详解
所以Queue.h代码如下:
#ifndef QUEUE_H
#define QUEUE_H
#include "throw.h"
// throw.h里面定义了一个ThrowException抛异常的宏,如下所示:
//#include <iostream>
//using namespace std;
//#define ThrowException(errMsg) {cout<<__FILE__<<" LINE"<<__LINE__<<": "<<errMsg<<endl; (throw errMsg);}
#include "LinkedList.h"
template < typename T>
class Queue : public LinkedList<T>
{
public:
inline void enqueue(const T &t) { LinkedList<T>::append(t); }
inline T dequeue()
{
if(LinkedList<T>::isEmpty()) { // 如果栈为空,则抛异常
ThrowException("Stack is empty ...");
}
T t = LinkedList<T>::get(0);
LinkedList<T>::remove(0);
return t;
}
inline T &head()
{
if(LinkedList<T>::isEmpty()) { // 如果栈为空,则抛异常
ThrowException("Stack is empty ...");
}
return LinkedList<T>::get(0);
}
inline const T &head() const
{
if(LinkedList<T>::isEmpty()) { // 如果栈为空,则抛异常
ThrowException("Stack is empty ...");
}
return LinkedList<T>::get(0);
}
};
#endif // QUEUE_H
int main(int argc, char *argv[])
{
Queue<int> queue;
cout<<"******* current length:"<<queue.length()<<endl;
for(int i = 0; i < 5; i++) {
cout<<"queue.enqueue:"<<i<<endl;
queue.enqueue(i);
}
cout<<"******* current length:"<<queue.length()<<endl;
while(!queue.isEmpty()) {
cout<<"queue.dequeue:"<<queue.dequeue()<<endl;
}
return 0;
}
运行打印:
以上是“C++中Queue队列类模版的示例分析”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。