日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

C++Stack棧類模版實例詳解_C 語言

作者:諾謙 ? 更新時間: 2022-04-28 編程語言

1.棧的介紹

棧的實現(xiàn)方式分為3

  • 基于靜態(tài)數(shù)組實現(xiàn),內(nèi)部預(yù)設(shè)一個很大的數(shù)組對象, 實現(xiàn)簡單,缺點是空間受限。
  • 基于動態(tài)數(shù)組實現(xiàn),內(nèi)部預(yù)設(shè)一個容量值,然后分配一段內(nèi)存空間數(shù)組,如果入棧大于默認(rèn)容量值時,則再次擴(kuò)大分配新的內(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 
//using namespace std;
//#define ThrowException(errMsg)  {cout<<__FILE__<<" LINE"<<__LINE__<<": "<
class Stack : public Vector
{
public:
    T pop()
    {
        if(Vector::isEmpty()) {        // 如果棧為空,則拋異常
            ThrowException("Stack is empty ...");
        }
        T t = Vector::data()[Vector::length() - 1];
        Vector::resize(Vector::length() - 1);
        return  t;
    }
    // 入棧,實際就是append尾部添加成員
    void push(const T &t)
    {
        Vector::append(t);
    }
    T &top()
    {
        if(Vector::isEmpty()) {
            ThrowException("Stack is empty ...");
        }
        return Vector::data()[Vector::length() - 1];
    }
    const T &top() const
    {
        if(Vector::isEmpty()) {
            ThrowException("Stack is empty ...");
        }
        return Vector::data()[Vector::length() - 1];
    }
};
#endif // Stack_H

3.代碼測試

int main(int argc, char *argv[])
{
    Stack stack;
    cout<<"******* current length:"<

運行打印:

總結(jié)

原文鏈接:https://blog.csdn.net/qq_37997682/article/details/123123143

欄目分類
最近更新