非类型类别模板参数

本文介绍了一个通用模板栈类的实现,该栈类使用数组作为内部数据结构,并提供了基本的栈操作,如压栈(push)、弹栈(pop)、获取栈顶元素(top)等。文章通过具体的代码示例展示了如何定义和使用这个模板栈类。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. #include "stdafx.h"
  2. #include <stdexcept>
  3. #include <iostream>
  4. #include <string>
  5. using namespace std;
  6. template <class T, int MAX_SIZE>
  7. class CStack
  8. {
  9. public:
  10.     CStack();
  11.     ~CStack();
  12. public:
  13.     void push(T const&);
  14.     void pop();
  15.     T top() const;
  16.     bool empty() const;
  17.     bool full() const;
  18. private:
  19.     T m_arrData[MAX_SIZE];
  20.     int m_nCurrPos;
  21. };
  22. template <class T, int MAX_SIZE>
  23. CStack<T, MAX_SIZE>::CStack():m_nCurrPos(0)
  24. {
  25. }
  26. template <class T, int MAX_SIZE>
  27. CStack<T, MAX_SIZE>::~CStack()
  28. {
  29. }
  30. template <class T, int MAX_SIZE>
  31. bool CStack<T, MAX_SIZE>::empty() const
  32. {
  33.     return 0 == m_nCurrPos;
  34. }
  35. template <class T, int MAX_SIZE>
  36. bool CStack<T, MAX_SIZE>::full() const
  37. {
  38.     return MAX_SIZE == m_nCurrPos;
  39. }
  40. template <class T, int MAX_SIZE>
  41. void CStack<T, MAX_SIZE>::push(const T &elem)
  42. {
  43.     if (m_nCurrPos == MAX_SIZE)
  44.     {
  45.         throw out_of_range("Stack<>::push stack is full!");
  46.     }
  47.     m_arrData[m_nCurrPos++] = elem;
  48. }
  49. template <class T, int MAX_SIZE>
  50. void CStack<T, MAX_SIZE>::pop()
  51. {
  52.     if (m_nCurrPos <= 0)
  53.     {
  54.         throw out_of_range("Stack<>::pop stack is empty!");
  55.     }
  56.     --m_nCurrPos;
  57. }
  58. template <class T, int MAX_SIZE>
  59. T CStack<T, MAX_SIZE>::top() const
  60. {
  61.     if (m_nCurrPos <= 0)
  62.     {
  63.         throw out_of_range("Stack<>::pop stack is empty!");
  64.     }
  65.     return m_arrData[m_nCurrPos - 1];
  66. }
  67. int main()
  68. {
  69.     CStack<int, 20> int20Stack;
  70.     CStack<int, 40> int40Stack;
  71.     CStack<string, 40> stringStack;
  72.     //test int stack;
  73.     int20Stack.push(7);
  74.     cout << int20Stack.top() << endl;
  75.     int20Stack.pop();
  76.     //string stack;
  77.     stringStack.push("hello");
  78.     cout << stringStack.top() << endl;
  79.     stringStack.pop();
  80.     return 0;
  81. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值