fork(1) download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. #include<cstdlib>
  5. #include <string>
  6. #define DEFAULT_INITIAL_SIZE_ 2
  7.  
  8. using namespace std;
  9.  
  10. template<class B>
  11. class Stack{
  12. private:
  13. B*data;
  14. long size;
  15. long top;
  16.  
  17. public:
  18.  
  19. Stack();
  20.  
  21. Stack(long size);
  22.  
  23. ~Stack(){
  24.  
  25. delete[] data;
  26. }
  27.  
  28. void push(B element){
  29. if(this->top==this->size){
  30.  
  31. stack_resize();
  32. }
  33. this->data[this->top]=element;
  34. this->top++;
  35.  
  36. }
  37.  
  38. friend ostream& operator<<(ostream& os,const Stack & s){
  39. if(s.top==0) return os<<"Stack is empty - nothing to print";
  40. else{
  41. for(int i=0;i<s.top;i++){
  42. os<<s.data[i]<<" ";
  43. }
  44. return os<<"\n";
  45. }
  46. }
  47.  
  48. int pop(){
  49. if(this->top==0){
  50. cout<<"Can't pop from empty stack"<<endl;
  51. exit(1);
  52. }else{
  53. this->top--;
  54. return *(this->data+this->top);
  55. }
  56. }
  57.  
  58. bool is_empty(){
  59. if(this->top==0) return true;
  60. else return false;
  61.  
  62. }
  63.  
  64. void clear(){
  65. this->top=0;
  66. }
  67.  
  68. private:
  69. void stack_resize(){
  70. B*temporary_data=new B[2*(this->size)];
  71. for(int i=0;i<(this->size);i++){
  72.  
  73. temporary_data[i]=(this->data[i]);
  74. }
  75.  
  76. delete[] this->data;
  77.  
  78. this->data=temporary_data;
  79. this->size=2*(this->size);
  80. }
  81.  
  82. };
  83. template<class B>
  84. Stack<B>::Stack():size(2), top(0){
  85.  
  86.  
  87. try{
  88. data=new B[2];
  89. }catch(bad_alloc& ex){
  90. cout<<ex.what()<<endl;
  91. //destruktor ???
  92. }
  93. }
  94.  
  95. template<class B>
  96. Stack<B>::Stack(long size){
  97.  
  98. if(size<=0){
  99.  
  100. data=new B[2];
  101. this->size=2;
  102. this->top=0;
  103. }
  104. else{
  105.  
  106. try{
  107. this->size=size;
  108. this->top=0;
  109. data=new B[size];
  110. }catch(bad_alloc& ex){
  111. cout<<ex.what()<<endl;
  112. //destruktor ???
  113. }
  114. }
  115. }
  116.  
  117.  
  118. int main() {
  119. Stack<string> s1;
  120. s1.push(string("abab"));
  121. s1.push(string("abab2"));
  122. s1.push(string("abab3"));
  123.  
  124. cout << s1 << endl;
  125.  
  126. return 0;
  127. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
abab abab2 abab3