C++Stack棧類模版實例詳解
1.棧的介紹
棧的實現(xiàn)方式分為3種
- 基于靜態(tài)數(shù)組實現(xiàn),內(nèi)部預設一個很大的數(shù)組對象, 實現(xiàn)簡單,缺點是空間受限。
- 基于動態(tài)數(shù)組實現(xiàn),內(nèi)部預設一個容量值,然后分配一段內(nèi)存空間數(shù)組,如果入棧大于默認容量值時,則再次擴大分配新的內(nèi)存數(shù)組,并將舊數(shù)組拷貝至新數(shù)組及釋放舊數(shù)組.
- 基于雙向循環(huán)鏈表實現(xiàn)
棧的函數(shù)需要實現(xiàn)如下所示:
T pop() :
出棧并返回棧頂元素void push(const T &t) :
入棧const T & top() const :
獲取const類型棧頂元素T &top() :
獲取棧頂元素int length() const:
獲取數(shù)量(父類已經(jīng)實現(xiàn))void clear(): 清空棧(父類已經(jīng)實現(xiàn))
本章,我們實現(xiàn)的?;趧討B(tài)數(shù)組實現(xiàn),它的父類是我們之前實現(xiàn)的Vector類:
C++ 動態(tài)數(shù)組模版類Vector實例詳解
所以代碼實現(xiàn)會非常簡單.
2.棧實現(xiàn)
代碼如下所示:
#ifndef Stack_H #define Stack_H #include "throw.h" // throw.h里面定義了一個ThrowException拋異常的宏,如下所示: //#include <iostream> //using namespace std; //#define ThrowException(errMsg) {cout<<__FILE__<<" LINE"<<__LINE__<<": "<<errMsg<<endl; (throw errMsg);} #include "Vector.h" template<class T> class Stack : public Vector<T> { public: T pop() { if(Vector<T>::isEmpty()) { // 如果棧為空,則拋異常 ThrowException("Stack is empty ..."); } T t = Vector<T>::data()[Vector<T>::length() - 1]; Vector<T>::resize(Vector<T>::length() - 1); return t; } // 入棧,實際就是append尾部添加成員 void push(const T &t) { Vector<T>::append(t); } T &top() { if(Vector<T>::isEmpty()) { ThrowException("Stack is empty ..."); } return Vector<T>::data()[Vector<T>::length() - 1]; } const T &top() const { if(Vector<T>::isEmpty()) { ThrowException("Stack is empty ..."); } return Vector<T>::data()[Vector<T>::length() - 1]; } }; #endif // Stack_H
3.代碼測試
int main(int argc, char *argv[]) { Stack<int> stack; cout<<"******* current length:"<<stack.length()<<endl; for(int i = 0; i < 5; i++) { cout<<"stack.push:"<<i<<endl; stack.push(i); } cout<<"******* current length:"<<stack.length()<<endl; while(!stack.isEmpty()) { cout<<"stack.pop:"<<stack.pop()<<endl; } return 0; }
運行打印:
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注腳本之家的更多內(nèi)容!
相關文章
C 語言實現(xiàn)一個簡單的 web 服務器的原理解析
這篇文章主要介紹了C 語言實現(xiàn)一個簡單的 web 服務器的原理解析,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-11-11c語言鏈表基本操作(帶有創(chuàng)建鏈表 刪除 打印 插入)
這篇文章主要介紹了c語言鏈表基本操作,大家參考使用吧2013-12-12Visual Studio 如何創(chuàng)建C/C++項目問題
這篇文章主要介紹了Visual Studio 如何創(chuàng)建C/C++項目問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02圖解AVL樹數(shù)據(jù)結(jié)構輸入與輸出及實現(xiàn)示例
這篇文章主要為大家介紹了C++圖解AVL樹數(shù)據(jù)結(jié)構輸入與輸出操作示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05