Something went wrong. Try again.
Java--'s containers projects.intra.42.fr/projects/cpp-module-09
Something went wrong. Try again.
1.6 kB · 85 lines
C++
at main
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586#include <RPN.hpp>
#include <cctype>#include <stack>#include <stdexcept>
RPN::RPN() {}
RPN::RPN(const RPN& other) { (void)other; }
enum Operator { PLUS, MINUS, MULTIPLY, DIVIDE };
static bool isOperator(char c) { return c == '+' || c == '-' || c == '*' || c == '/'; }
static Operator getOperator(char c) { switch (c) { case '+': return PLUS; case '-': return MINUS; case '*': return MULTIPLY; case '/': return DIVIDE; default: throw std::runtime_error(""); }}
static long operate(const Operator& op, const long& a, const long& b) { switch (op) { case PLUS: return a + b; case MINUS: return a - b; case MULTIPLY: return a * b; case DIVIDE: return a / b; }}
long RPN::evaluate(const std::string& expression) const { std::stack<long> stack;
for (size_t i = 0; i < expression.size(); ++i) { if (expression[i] == ' ') continue;
if (isOperator(expression[i])) { if (stack.size() < 2) throw std::runtime_error("");
const Operator op = getOperator(expression[i]);
const long b = stack.top(); stack.pop(); const long a = stack.top(); stack.pop();
if (op == DIVIDE && b == 0) throw std::runtime_error("");
stack.push(operate(op, a, b)); } else if (std::isdigit(static_cast<unsigned char>(expression[i]))) { stack.push(expression[i] - '0'); } else { throw std::runtime_error(""); } }
if (stack.size() != 1) throw std::runtime_error("");
return stack.top();}
RPN& RPN::operator=(const RPN& other) { if (this == &other) return *this;
return *this;}
RPN::~RPN() {}