這道題目的意義重大,標誌著我要全面學習 C++ 了。以模板實作堆疊,剛好可以一次練到抽象基類、純虛函式、繼承與動態記憶體配置。
- #include<iostream>
- #include<stdlib.h>
- using namespace std;
- template <class elemtype>
- class stack {
- public:
- virtual bool is_empty() const = 0;
- virtual void push(const elemtype &x) = 0;
- virtual elemtype pop() = 0;
- virtual elemtype top() const = 0;
- virtual ~stack() {}
- };
- template <class elemtype>
- class set_stack: public stack <elemtype> {
- private:
- elemtype *elem;
- int top_p;
- int max_size;
- void double_space();
- public:
- set_stack(int init_size = 10) {
- elem = new elemtype [init_size];
- max_size = init_size;
- top_p = -1;
- }
- ~set_stack() { delete[] elem; }
- bool is_empty() const { return top_p == -1; }
- void push(const elemtype &x) {
- if(top_p == max_size - 1) {
- double_space();
- }
- elem[++top_p] = x;
- }
- elemtype pop() {
- return elem[--top_p];
- }
- elemtype top() const {
- return elem[top_p];
- }
- };
- template <class elemtype>
- void set_stack<elemtype>::double_space(){
- elemtype *tmp = elem;
- elem = new elemtype[2*max_size];
- for(int i = 0; i < max_size; ++i) {
- elem[i] = tmp[i];
- }
- max_size *= 2;
- delete[] tmp;
- };
- int main()
- {
- set_stack<int> *s = new set_stack<int>(10);
- cout<<s->is_empty();
- for(int i = 1; i <= 20; i++) {
- s->push(i*10);
- }
- for(int i = 1; i <=20 ; i++) {
- cout << s->top() << endl;
- s->pop();
- }
- cout<<s->top();
- return 0;
- }
幾個設計上的細節
抽象基類 stack 把四個操作宣告成純虛函式,並提供虛擬解構子,確保透過基底指標 delete 時能正確解構——這點在 C++ 中經常被忽略卻至關重要。double_space() 的擴容策略是「配置兩倍空間、搬移舊資料、釋放舊記憶體」,因此 push 的攤提時間為常數。
程式刻意示範了初始容量 10 卻連續 push 20 次的情境,用來驗證自動擴容是否真的生效。若要更嚴謹,可再補上 pop() 與 top() 在空堆疊時的邊界檢查,目前版本在空堆疊呼叫 top 是未定義行為。
呵呵,加油。