From cdb438cfa93d65a1497b5885823a0af0015092f7 Mon Sep 17 00:00:00 2001 From: Alma Dejus Date: Sat, 28 Oct 2023 15:42:38 +0200 Subject: [PATCH] Added smart pointers --- src/expression.cc | 44 ++++++++++++++++++++++++++++---------------- src/operators.h | 1 + 2 files changed, 29 insertions(+), 16 deletions(-) diff --git a/src/expression.cc b/src/expression.cc index 67378b8..b5b3463 100644 --- a/src/expression.cc +++ b/src/expression.cc @@ -8,64 +8,70 @@ Expression::Expression(const std::string & expression) std::stringstream iss{post_string}; Token token{}; - std::stack stack{}; - Node * new_node{nullptr}; + std::stack> stack{}; while (iss >> token) { if (token.is_integer()) { - new_node = new Const_int{std::stoi(token)}; + stack.push(std::make_unique(std::stoi(token))); } else if (token.is_decimal()) { - new_node = new Const_double{std::stod(token)}; + stack.push(std::make_unique(std::stod(token))); } else if ( isalpha(token.at(0))) { + // Behövs ej pga smartpekare + /* while(!stack.empty()) { delete stack.top(); stack.pop(); - } + }*/ throw std::logic_error("Variables are not implemented"); + } else if (token.is_operator()) { - Node * rhs{stack.top()}; + std::unique_ptr rhs = std::move(stack.top()); stack.pop(); - Node * lhs{stack.top()}; + std::unique_ptr lhs = std::move(stack.top()); stack.pop(); + if (lhs == nullptr || rhs == nullptr) { + // Behövs ej pga smartpekare + /* while(!stack.empty()) { delete stack.top(); stack.pop(); - } + }*/ throw std::logic_error("Missing operands"); + } if (token == "+") { - new_node = new Addition{lhs, rhs}; + stack.push(std::make_unique(lhs.release(), rhs.release())); } else if (token == "-") { - new_node = new Subtraction{lhs, rhs}; + stack.push(std::make_unique(lhs.release(), rhs.release())); } else if (token == "/") { - new_node = new Division{lhs, rhs}; + stack.push(std::make_unique(lhs.release(), rhs.release())); } else if (token == "*") { - new_node = new Multiplication{lhs, rhs}; + stack.push(std::make_unique(lhs.release(), rhs.release())); } else if (token == "^") { - new_node = new Exponent{lhs, rhs}; + stack.push(std::make_unique(lhs.release(), rhs.release())); } else { @@ -74,29 +80,35 @@ Expression::Expression(const std::string & expression) } else { + // Behövs ej pga smartpekare + /* while(!stack.empty()) { delete stack.top(); stack.pop(); - } + }*/ throw std::logic_error("Undefined characters in expression"); + } - stack.push(new_node); } if (stack.size() == 0) { throw std::logic_error("Empty expression"); } - expression_root = stack.top(); + expression_root = stack.top().release(); + if (stack.size() > 1) { + // Behövs ej pga smartpekare + /* while(!stack.empty()) { delete stack.top(); stack.pop(); } + */ throw std::logic_error("Missing operators"); } } diff --git a/src/operators.h b/src/operators.h index bfe5bb6..fb7f929 100644 --- a/src/operators.h +++ b/src/operators.h @@ -5,6 +5,7 @@ #include #include #include +#include #include "node.h" -- 2.30.2