1. 程式人生 > >C++棧的用法及棧的實現

C++棧的用法及棧的實現

  1. 首先看一下原c++棧的方法的基本用法:
    1. push(): 向棧內壓入一個成員;
    2. pop(): 從棧頂彈出一個成員;
    3. empty(): 如果棧為空返回true,否則返回false;
    4. top(): 返回棧頂,但不刪除成員;
    5. size(): 返回棧內元素的大小;
  2. 程式碼示例:
#include<iostream>
#include<stack>
using namespace std;

int main()
{
    stack <int>stk;
    //入棧
    for(int i=0;i<50;i++){
        stk.push(i);
    }
    cout
<<"棧的大小:"<<stk.size()<<endl; while(!stk.empty()) { cout<<stk.top()<<endl; stk.pop(); } cout<<"棧的大小:"<<stk.size()<<endl; return 0; }
  1. 接下來我們自己寫棧,這時就需要用到c++中的模板類(template)
#include<iostream>
#include<stdlib.h>
using namespace
std; #define MAXSIZE 0xffff template<class type> class my_stack { int top; type* my_s; int maxsize; public: my_stack():top(-1),maxsize(MAXSIZE) { my_s=new type[maxsize]; if(my_s==NULL) { cerr<<"動態儲存分配失敗!"<<endl; exit(1
); } } my_stack(int size):top(-1),maxsize(size) { my_s=new type[maxsize]; if(my_s==NULL) { cerr<<"動態儲存分配失敗!"<<endl; exit(1); } } ~my_stack() { delete[] my_s; } //是否為空 bool Empty(); //壓棧 void Push(type tp); //返回棧頂元素 type Top(); //出棧 void Pop(); //棧大小 int Size(); }; template<class type> bool my_stack<type>::Empty() { if(top==-1){ return true; } else return false; } template<class type> type my_stack<type>::Top() { if(top!=-1) { return my_s[top]; } else { cout<<"棧空\n"; exit(1); } } template<class type> void my_stack<type>::Push(type tp) { if(top+1<maxsize) { my_s[++top]=tp; } else { cout<<"棧滿\n"; exit(1); } } template<class type> void my_stack<type>::Pop() { if(top>=0) { top--; } else { cout<<"棧空\n"; exit(1); } } template<class type> int my_stack<type>::Size() { return top+1; }
  1. 然後就可以在另一個cpp檔案中使用它了(記得include):
#include<iostream>
#include "my_stack.cpp"

using namespace std;

int main()
{
    my_stack<int> stk;
    for(int i=0;i<50;i++){
        stk.Push(i);
    }
    cout<<"棧的大小:"<<stk.Size()<<endl;
    while(!stk.Empty())
    {
        cout<<stk.Top()<<endl;
        stk.Pop();
    }
    cout<<"棧的大小:"<<sizeof(stk)<<endl;
    return 0;
}
  1. 在編寫程式碼的時候我突然很好奇,size()和sizeof輸出的區別,然後我用我寫的棧做了嘗試:
#include<iostream>
#include<stack>
#include "my_stack.cpp"

using namespace std;

int main()
{
    my_stack<int> stk;
    stack<int> s;
    for(int i=0;i<20;i++){
        stk.Push(i);
        s.push(i);
    }
    cout<<"mysize()="<<stk.Size()<<"\nmysizeof="<<sizeof(stk)<<endl;
    cout<<"size()="<<s.size()<<"\nsizeof="<<sizeof(s)<<endl;
    return 0;
}

輸出:
mysize()=20
mysizeof=12
size()=20
sizeof=40

並且可以看到我寫的棧類的變數只有三個整型(一個template型),剛好12個位元組,由此可知c++提供的棧內不止我寫的這麼簡單,光變數就佔40個位元組