fork download
  1. //
  2. // a toy calculator in reverse Polish notation
  3. // similar to dc in Unix
  4. // this illustrates the stack pointer idioms
  5. // *sp++ and so on
  6. // Hayo Thielecke 12.1.2014
  7.  
  8. #include <stdio.h>
  9. #include <string.h>
  10. #include <stdlib.h>
  11. #include <iostream>
  12.  
  13. template<typename T>
  14. class stackArray {
  15. public:
  16.  
  17. const int stacksize = 100;
  18.  
  19. T stack[100];
  20. T *sp;
  21.  
  22. // invariant: sp points to first free element
  23.  
  24. stackArray<T>() {
  25. sp = stack; // Here we go.
  26. };
  27.  
  28. ~stackArray<T>() {
  29. //delete [] stack;
  30. // free(stack);
  31. sp = NULL;
  32. };
  33.  
  34.  
  35. void push(T n)
  36. {
  37. if (sp < stack + stacksize - 1) {
  38. *sp++ = n;
  39. } else {
  40. fprintf(stderr, "Stack overflow!\n\n");
  41. exit(1);
  42. }
  43. }
  44.  
  45. T pop()
  46. {
  47. if (sp > stack) {
  48. return *--sp;
  49. } else {
  50. fprintf(stderr, "Stack underflow!\n\n");
  51. exit(1);
  52. }
  53. }
  54.  
  55. int isempty() {
  56. if (sp <= stack) {
  57. return 1;
  58. }
  59. return 0;
  60. }
  61.  
  62. void printstack()
  63. {
  64. int *p = sp - 1;
  65. printf("\nStack is: ");
  66. while (p >= stack)
  67. printf("%6d", *p--);
  68. printf("\n\n");
  69. }
  70.  
  71. void applytoall(void (*func) (T&))
  72. {
  73. T *p = sp - 1;
  74. while (p >= stack)
  75. func(*p--);
  76. printf("\n");
  77. }
  78.  
  79.  
  80.  
  81. };
  82.  
  83.  
  84. void plusone(int &p)
  85. {
  86. p = p + 1;
  87. }
  88.  
  89. int main() {
  90. stackArray<int> g;
  91. g.push(1);
  92. g.push(2);
  93. g.push(3);
  94. int empty = g.isempty();
  95. std::cout << "HEY" << empty << "\n";
  96. g.printstack();
  97. g.pop();
  98. g.printstack();
  99. g.applytoall(plusone);
  100. g.printstack();
  101. }
  102.  
  103.  
  104.  
Success #stdin #stdout 0s 3140KB
stdin
Standard input is empty
stdout
HEY0

Stack is:      3     2     1


Stack is:      2     1



Stack is:      3     2