fork download
  1. #include <iostream>
  2. // using namespace std ; // unlearn the habbit of doing this.
  3. #include <memory> // for unique_ptr
  4.  
  5. class Stack
  6. {
  7. // note: class is private by default.
  8. // unique_ptr will automatically free memory for us.
  9. using ptr_t = std::unique_ptr<int[]>;
  10.  
  11. ptr_t base_;
  12. int* top_;
  13. int* end_;
  14.  
  15. public :
  16. Stack(int size=100)
  17. : base_(new int[size])
  18. , top_(base_.get())
  19. , end_(top_ + size)
  20. {}
  21.  
  22. bool empty() const
  23. { return top_ == base_.get(); }
  24.  
  25. bool full() const
  26. { return top_ == end_; }
  27.  
  28. // don't print errors from a library
  29. bool push(int value)
  30. {
  31. if (full()) // written in terms of our own members
  32. return false;
  33. *(top_++) = value;
  34. return true;
  35. }
  36.  
  37. bool pop()
  38. {
  39. if (empty()) // written in terms of our own members
  40. return false;
  41. --top_;
  42. return true;
  43. }
  44.  
  45. const int& read_top() const // const ref so it's not modifiable
  46. { return *(top_-1); }
  47.  
  48. int size() const { return end_ - top_; }
  49. int capacity() const { return end_ - base_.get(); }
  50.  
  51. std::ostream& print(std::ostream& to)
  52. {
  53. to << "Stack is ";
  54. for (int* ptr = base_.get(); ptr != top_; ++ptr)
  55. to << *ptr << ' ';
  56. to << '\n';
  57. return to;
  58. }
  59.  
  60. // or we could do this:
  61. friend std::ostream& operator << (std::ostream& to, const Stack& s)
  62. {
  63. to << '[';
  64. for (int* ptr = s.base_.get(); ptr != s.top_; ++ptr) {
  65. to << *ptr << ',';
  66. }
  67. return to << ']';
  68. }
  69. };
  70.  
  71. int main()
  72. {
  73. Stack s(5);
  74. s.push(1);
  75. s.push(2);
  76. s.push(3);
  77. s.print(std::cout);
  78. std::cout << "stack is: " << s << '\n';
  79. }
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
Stack is 1 2 3 
stack is: [1,2,3,]