fork download
  1. #include <iostream>
  2. #include <cassert>
  3. #include <cstring>
  4.  
  5.  
  6. template<typename T>
  7. class stack {
  8. public:
  9. stack(const size_t size = s_incrementSize) : m_index(-1) {
  10. assert(size > 0);
  11. m_memory = new T[size];
  12. m_size = size;
  13. }
  14.  
  15. ~stack() {
  16. for (size_t idx = 0; idx < m_index; ++idx) {
  17. m_memory[idx].~T();
  18. }
  19. }
  20.  
  21. void push(const T &data) {
  22. if (++m_index >= m_size) {
  23. size_t newSize = m_size + s_incrementSize;
  24. T *newMemory = new T[newSize];
  25. memcpy(newMemory, m_memory, sizeof(T) * m_index);
  26. delete[] m_memory;
  27. m_memory = newMemory;
  28. m_size = newSize;
  29. }
  30.  
  31. new (m_memory + m_index) T(data);
  32. }
  33.  
  34. T pop() {
  35. if (m_index >= 0) {
  36. T result = m_memory[m_index];
  37. m_memory[m_index--].~T();
  38. return result;
  39. } else {
  40. return T();
  41. }
  42. }
  43.  
  44. size_t size() const { return m_index + 1; }
  45.  
  46. T &operator[](const size_t index) const {
  47. assert(index >= 0);
  48. assert(index <= m_index);
  49.  
  50. return m_memory[index];
  51. }
  52.  
  53. private:
  54. static constexpr size_t s_incrementSize = 1000;
  55.  
  56. size_t m_index;
  57. size_t m_size;
  58. T *m_memory;
  59. };
  60.  
  61. int main(int argc, char **argv) {
  62. stack<int> s;
  63.  
  64. s.push(10);
  65. s.push(20);
  66. s.push(30);
  67.  
  68. while (s.size() > 0) {
  69. std::cout << " " << s.pop();
  70. }
  71.  
  72. return 0;
  73. }
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
 30 20 10