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

總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
C語言實現(xiàn)學(xué)生信息管理系統(tǒng)(單鏈表)
這篇文章主要為大家詳細(xì)介紹了C語言實現(xiàn)學(xué)生信息管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-01-01
C++ std::condition_variable 條件變量用法解析
condition_variable(條件變量)是 C++11 中提供的一種多線程同步機(jī)制,它允許一個或多個線程等待另一個線程發(fā)出通知,以便能夠有效地進(jìn)行線程同步,這篇文章主要介紹了C++ std::condition_variable 條件變量用法,需要的朋友可以參考下2023-09-09
解析bitmap處理海量數(shù)據(jù)及其實現(xiàn)方法分析
本篇文章是對bitmap處理海量數(shù)據(jù)及其實現(xiàn)的方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05
C++關(guān)于類結(jié)構(gòu)體大小和構(gòu)造順序,析構(gòu)順序的測試詳解
這篇文章主要介紹了C++類結(jié)構(gòu)體大小和構(gòu)造順序,析構(gòu)順序的測試,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08

