Advertisement
Korotkodul

stack

Dec 7th, 2021
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. #include <iostream>
  2. #include <stack>
  3. #include <string>
  4. #include <vector>
  5. #include <algorithm>
  6.  
  7. using namespace std;
  8.  
  9. vector <string> sig = {"*", "/", "+", "-"};
  10.  
  11. bool sgn(string x){
  12. bool r = 0;
  13. for (auto y: sig){
  14. if (y == x){
  15. r = 1;
  16. }
  17. }
  18. return r;
  19. }
  20.  
  21. int opr(string x, int a, int b){
  22. int res;
  23. if (x == "*") res = a * b;
  24. else if (x == "/") res = a / b;
  25. else if (x == "+") res = a + b;
  26. else if (x == "-") res = a - b;
  27. return res;
  28. }
  29.  
  30. int main()
  31. {
  32. vector <string> al;
  33. stack <int> go;
  34. string s;
  35. getline(cin, s);
  36. /*for (char l: s){
  37. cout<<l<<'\n';
  38. }*/
  39. int id = 0;
  40. string x = "";
  41. for (int i=0;i<s.size();++i){
  42. char l = s[i];
  43. if (l == ' ') {
  44. //cout<<i<<'\n';
  45. al.push_back(x);
  46. x = "";
  47.  
  48. }
  49. else{
  50. x += l;
  51. }
  52. }
  53. al.push_back(x);
  54. //for (auto x: al) cout<<x<<'\n';
  55. int dg;
  56. int a,b;
  57. int ans = 0;
  58. for (auto x: al){
  59. if (sgn(x)){
  60. //cout<<x<<'\n';
  61. a = go.top();
  62. go.pop();
  63. b = go.top();
  64. go.pop();
  65. ans = opr(x, a, b);
  66. go.push(ans);
  67. }
  68. else {
  69. dg = stoi(x);
  70. go.push(dg);
  71. }
  72. }
  73. cout<<"ans= "<<ans<<'\n';
  74. }
  75.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement