C++ Queue队列类模版实例详解
作者:诺谦
这篇文章主要为大家详细介绍C++ Queue队列类模版实例,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
1.队列的介绍
队列的定义
- 队列(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():清空队列(父类已经实现)
2.代码实现
本章,我们实现的队列基于链表形式实现,它的父类是我们之前实现的LinkedList类:
所以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_H3.测试运行
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;
}运行打印:

总结
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注脚本之家的更多内容!
