Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

C++ 實作帶自動擴容的堆疊類別(template 版)

這道題目的意義重大,標誌著我要全面學習 C++ 了。以模板實作堆疊,剛好可以一次練到抽象基類、純虛函式、繼承與動態記憶體配置。

  1. #include<iostream>
  2. #include<stdlib.h>
  3. using namespace std;
  4. template <class elemtype>
  5. class stack {
  6. public:
  7. virtual bool is_empty() const = 0;
  8. virtual void push(const elemtype &x) = 0;
  9. virtual elemtype pop() = 0;
  10. virtual elemtype top() const = 0;
  11. virtual ~stack() {}
  12. };
  13. template <class elemtype>
  14. class set_stack: public stack <elemtype> {
  15. private:
  16. elemtype *elem;
  17. int top_p;
  18. int max_size;
  19. void double_space();
  20. public:
  21. set_stack(int init_size = 10) {
  22. elem = new elemtype [init_size];
  23. max_size = init_size;
  24. top_p = -1;
  25. }
  26. ~set_stack() { delete[] elem; }
  27. bool is_empty() const { return top_p == -1; }
  28. void push(const elemtype &x) {
  29. if(top_p == max_size - 1) {
  30. double_space();
  31. }
  32. elem[++top_p] = x;
  33. }
  34. elemtype pop() {
  35. return elem[--top_p];
  36. }
  37. elemtype top() const {
  38. return elem[top_p];
  39. }
  40. };
  41. template <class elemtype>
  42. void set_stack<elemtype>::double_space(){
  43. elemtype *tmp = elem;
  44. elem = new elemtype[2*max_size];
  45. for(int i = 0; i < max_size; ++i) {
  46. elem[i] = tmp[i];
  47. }
  48. max_size *= 2;
  49. delete[] tmp;
  50. };
  51. int main()
  52. {
  53. set_stack<int> *s = new set_stack<int>(10);
  54. cout<<s->is_empty();
  55. for(int i = 1; i <= 20; i++) {
  56. s->push(i*10);
  57. }
  58. for(int i = 1; i <=20 ; i++) {
  59. cout << s->top() << endl;
  60. s->pop();
  61. }
  62. cout<<s->top();
  63. return 0;
  64. }

幾個設計上的細節

抽象基類 stack 把四個操作宣告成純虛函式,並提供虛擬解構子,確保透過基底指標 delete 時能正確解構——這點在 C++ 中經常被忽略卻至關重要。double_space() 的擴容策略是「配置兩倍空間、搬移舊資料、釋放舊記憶體」,因此 push 的攤提時間為常數。

程式刻意示範了初始容量 10 卻連續 push 20 次的情境,用來驗證自動擴容是否真的生效。若要更嚴謹,可再補上 pop() 與 top() 在空堆疊時的邊界檢查,目前版本在空堆疊呼叫 top 是未定義行為。

呵呵,加油。

Copyright © Linux教程網 All Rights Reserved