Stack.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. #pragma once
  2. #include "ReferenceCounter.h"
  3. namespace Framework
  4. {
  5. template<class T> class Stack : public ReferenceCounter
  6. {
  7. private:
  8. std::function<T()> nullSupplier;
  9. T* data;
  10. int size;
  11. int capacity;
  12. public:
  13. Stack(std::function<T()> nullSupplier)
  14. : ReferenceCounter(),
  15. nullSupplier(nullSupplier),
  16. data(0),
  17. size(0),
  18. capacity(0)
  19. {}
  20. Stack(T null)
  21. : Stack([null]() { return null; })
  22. {}
  23. Stack()
  24. : Stack([]() { return (T)0; })
  25. {}
  26. ~Stack()
  27. {
  28. if (data)
  29. {
  30. delete[] data;
  31. }
  32. }
  33. void push(T element)
  34. {
  35. if (size == capacity)
  36. {
  37. int newCapacity
  38. = capacity == 0
  39. ? 1
  40. : capacity * 2; // new variable is needed to avoid false
  41. // positive compiler warnings
  42. T* newData = new T[newCapacity];
  43. for (int i = 0; i < size; i++)
  44. {
  45. newData[i] = data[i];
  46. }
  47. capacity = newCapacity;
  48. if (data)
  49. {
  50. delete[] data;
  51. }
  52. data = newData;
  53. }
  54. data[size++] = element;
  55. }
  56. T pop()
  57. {
  58. if (size == 0)
  59. {
  60. return nullSupplier();
  61. }
  62. return data[--size];
  63. }
  64. T peek()
  65. {
  66. if (size == 0)
  67. {
  68. return nullSupplier();
  69. }
  70. return data[size - 1];
  71. }
  72. void reset()
  73. {
  74. size = 0;
  75. }
  76. int getSize()
  77. {
  78. return size;
  79. }
  80. int getCapacity()
  81. {
  82. return capacity;
  83. }
  84. T* getData()
  85. {
  86. return data;
  87. }
  88. };
  89. } // namespace Framework