C++_模板举例_使用模板实现集合类(堆栈)

  1. //stack集合类是一个简单的堆栈的实现。   
  2. //这里有两个模板参数,T和size,指定堆栈中的元素类型和堆栈中项数的最大值。   
  3. //push 和 pop成员函数添加和删除堆栈中的项,并在堆栈底部增加。   
  4. #include <iostream>   
  5. #include <algorithm>   
  6. #include <string>   
  7. using namespace std;  
  8. template <class T,int size> //出错点   
  9. class stack  
  10. {  
  11. private:  
  12.     T items[size];  
  13.     int top;  
  14.     const int MaxSize;  
  15. public:  
  16.     stack():MaxSize(size)  
  17.     {  
  18.         top=-1;//指向栈底   
  19.     }  
  20.     bool IsFull();  
  21.     bool IsEmpty();  
  22.     void push(const T item);  
  23.     T pop();  
  24. };  
  25.   
  26. template <class T,int size>  
  27. bool stack<T,size>::IsFull()  
  28. {  
  29.     if(top==MaxSize-1)  
  30.     {  
  31.         return true;  
  32.     }  
  33.     else  
  34.     {  
  35.         return false;  
  36.     }  
  37. }  
  38.   
  39. template <class T,int size>  
  40. bool stack<T,size>::IsEmpty()  
  41. {  
  42.     if (top==-1)  
  43.     {  
  44.           
  45.         return true;  
  46.     }  
  47.     else  
  48.     {  
  49.         return false;  
  50.     }  
  51. }  
  52.   
  53. template <class T,int size>//出错点   
  54. void stack<T,size>::push(const T item)  
  55. {  
  56.     if (IsFull())  
  57.     {  
  58.         cout<<"stack is full"<<endl;  
  59.         return;  
  60.     }  
  61.     else  
  62.     {  
  63.         items[++top]=item;  
  64.     }  
  65. }  
  66.   
  67. template <class T,int size>  
  68. T stack<T,size>::pop()  
  69. {  
  70.     if (!IsEmpty())  
  71.     {  
  72.         return items[top--];  
  73.     }  
  74.     else  
  75.     {  
  76.         cout<<"栈空"<<endl;  
  77.         return 0;  
  78.     }  
  79. }  
  80.   
  81. void main()  
  82. {  
  83.     //stack<string,5> s;//栈中存放字符串   
  84.     stack<int,5> s;   //栈中存放整型数据   
  85.     while(!s.IsFull())  
  86.     {  
  87.         //s.push("123");//字符串入栈   
  88.         s.push(1);//整型数据入栈   
  89.     }  
  90.     while(!s.IsEmpty())  
  91.     {  
  92.         cout<<s.pop()<<endl;  
  93.     }  
  94.     system("pause");  
  95. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值