C++?Queue隊(duì)列類模版實(shí)例詳解
更新時(shí)間:2022年02月25日 16:37:44 作者:諾謙
這篇文章主要為大家詳細(xì)介紹C++?Queue隊(duì)列類模版實(shí)例,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
1.隊(duì)列的介紹
隊(duì)列的定義
- 隊(duì)列(Queue)是一種線性存儲結(jié)構(gòu)。它有以下幾個(gè)特點(diǎn):
- 按照"先進(jìn)先出(FIFO, First-In-First-Out)"方式進(jìn)出隊(duì)列。
- 隊(duì)列只允許在"隊(duì)首"進(jìn)行取出操作(出隊(duì)列),在"隊(duì)尾"進(jìn)行插入操作(入隊(duì)列 )
隊(duì)列實(shí)現(xiàn)的方式有兩種
- 基于動態(tài)數(shù)組實(shí)現(xiàn)
- 基于鏈表形式實(shí)現(xiàn)
隊(duì)列需要實(shí)現(xiàn)的函數(shù)
T dequeue() :出隊(duì)列,并返回取出的元素void enqueue(const T &t) :入隊(duì)列T &head() :獲取隊(duì)首數(shù)據(jù),但是不會被取出const T &head() const :獲取const類型隊(duì)首數(shù)據(jù)int length() const:獲取數(shù)量(父類已經(jīng)實(shí)現(xiàn))void clear():清空隊(duì)列(父類已經(jīng)實(shí)現(xiàn))
2.代碼實(shí)現(xiàn)
本章,我們實(shí)現(xiàn)的隊(duì)列基于鏈表形式實(shí)現(xiàn),它的父類是我們之前實(shí)現(xiàn)的LinkedList類:
所以Queue.h代碼如下:
#ifndef QUEUE_H
#define QUEUE_H
#include "throw.h"
// throw.h里面定義了一個(gè)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.測試運(yùn)行
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;
}運(yùn)行打印:

總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
C++編程中的數(shù)據(jù)類型和常量學(xué)習(xí)教程
這篇文章主要介紹了C++編程中的數(shù)據(jù)類型和常量學(xué)習(xí)教程,是C++入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下2015-09-09
深入分析C語言中結(jié)構(gòu)體指針的定義與引用詳解
本篇文章是對C語言中結(jié)構(gòu)體指針的定義與引用進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05

