tstack.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #ifndef _TStack_H_
  2. #define _TStack_H_
  3. //////////////////////////////////////////////////////////////////////////////
  4. //
  5. // Stack Template
  6. //
  7. //////////////////////////////////////////////////////////////////////////////
  8. template<class ValueType>
  9. class TStack {
  10. protected:
  11. ValueType* m_pvalue;
  12. int m_count;
  13. int m_countAlloc;
  14. public:
  15. TStack(int countAlloc = 0) :
  16. m_count(0),
  17. m_countAlloc(countAlloc)
  18. {
  19. ZAssert(m_countAlloc >= 0);
  20. if (m_countAlloc == 0) {
  21. m_pvalue = NULL;
  22. } else {
  23. m_pvalue = new ValueType[m_countAlloc];
  24. }
  25. }
  26. ~TStack()
  27. {
  28. if (m_pvalue) {
  29. delete[] m_pvalue;
  30. }
  31. }
  32. ValueType& operator[](int index) const
  33. {
  34. ZAssert(index >= 0 && index < m_count);
  35. return m_pvalue[m_count - index - 1];
  36. }
  37. void Push(const ValueType& value)
  38. {
  39. if (m_count == m_countAlloc) {
  40. if (m_countAlloc == 0) {
  41. m_countAlloc = 1;
  42. } else {
  43. m_countAlloc *= 2;
  44. }
  45. ValueType* m_pvalueNew = new ValueType[m_countAlloc];
  46. for(int index = 0; index < m_count; index++) {
  47. m_pvalueNew[index] = m_pvalue[index];
  48. }
  49. delete[] m_pvalue;
  50. m_pvalue = m_pvalueNew;
  51. }
  52. m_pvalue[m_count] = value;
  53. m_count++;
  54. }
  55. ValueType Pop()
  56. {
  57. ZAssert(m_count > 0);
  58. m_count--;
  59. return m_pvalue[m_count];
  60. }
  61. int GetCount() const
  62. {
  63. return m_count;
  64. }
  65. };
  66. //////////////////////////////////////////////////////////////////////////////
  67. //
  68. // Stack Object
  69. //
  70. //////////////////////////////////////////////////////////////////////////////
  71. template<class ValueType>
  72. class TStackObject : public IObject, public TStack<ValueType> {
  73. };
  74. #endif