Advertisement
mfgnik

Untitled

Jun 28th, 2020
1,317
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.96 KB | None | 0 0
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <stack>
  4. #include <string>
  5. #include <unordered_set>
  6. #include <vector>
  7.  
  8. std::vector<std::string> Split(const std::string &string, const std::string &delimiter = " ") {
  9.     std::vector<std::string> split;
  10.     size_t prev_pos = 0;
  11.     size_t pos = string.find(delimiter);
  12.     while (true) {
  13.         split.push_back(string.substr(prev_pos, pos - prev_pos));
  14.         if (pos == std::string::npos) {
  15.             break;
  16.         }
  17.         prev_pos = pos + delimiter.size();
  18.         pos = string.find(delimiter, prev_pos);
  19.     }
  20.     return split;
  21. }
  22.  
  23. std::pair<bool, int> EvaluateExpression(const std::vector<std::string> &expression) {
  24.     std::unordered_set<std::string> operations{"+", "-", "*", "/"};
  25.     std::vector<int> stack;
  26.     for (auto element : expression) {
  27.         int result;
  28.         if (operations.count(element)) {
  29.             if (stack.size() < 2) {
  30.                 return {false, 0};
  31.             }
  32.             auto first_el = stack.back();
  33.             stack.pop_back();
  34.             auto second_el = stack.back();
  35.             stack.pop_back();
  36.             if (element == "+") {
  37.                 result = first_el + second_el;
  38.             } else if (element == "-") {
  39.                 result = -first_el + second_el;
  40.             } else if (element == "*") {
  41.                 result = first_el * second_el;
  42.             } else if (element == "/") {
  43.                 result = second_el / first_el - (first_el * second_el < 0);
  44.             }
  45.         } else {
  46.             result = std::stoi(element);
  47.         }
  48.         stack.push_back(result);
  49.     }
  50.     if (stack.size() != 1) {
  51.         return {false, 0};
  52.     }
  53.     return {true, stack.back()};
  54. }
  55.  
  56.  
  57. int main() {
  58.     std::string expression;
  59.     std::getline(std::cin, expression);
  60.     auto result = EvaluateExpression(Split(expression));
  61.     if (result.first) {
  62.         std::cout << result.second;
  63.     } else {
  64.         std::cout << "ERROR";
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement