while (iss >> token)
{
- std::cout << token << std::endl;
-
if (token.is_integer())
{
new_node = new Const_int{std::stoi(token)};
}
else if (token.is_operator())
{
- Node * lhs{stack.top()};
- stack.pop();
Node * rhs{stack.top()};
stack.pop();
+ Node * lhs{stack.top()};
+ stack.pop();
if (lhs == nullptr || rhs == nullptr)
{
throw std::logic_error("Missing operands");
}
- switch (operator_string_map[token])
+ if (token == "+")
{
- case ADDITION:
new_node = new Addition{*lhs, *rhs};
- break;
- case SUBTRACTION:
+ }
+ else if (token == "-")
+ {
new_node = new Subtraction{*lhs, *rhs};
- break;
- case DIVISION:
- new_node = new Division{*lhs, *rhs};
- break;
- case MULTIPLICATION:
+ }
+ else if (token == "/")
+ {
+ new_node = new Division{*lhs, *rhs};
+ }
+ else if (token == "*")
+ {
new_node = new Multiplication{*lhs, *rhs};
- break;
- case EXPONENT:
+ }
+ else if (token == "^")
+ {
new_node = new Exponent{*lhs, *rhs};
- break;
- default:
+ }
+ else
+ {
throw std::logic_error("Operator not implemented");
- break;
}
}
else
expression_root = stack.top();
}
-std::string Expression::to_string(StringFormat s_format) const
+std::string Expression::to_infix_string() const
{
- switch(s_format)
- {
- case PREFIX:
- return expression_root->get_prefix();
- case POSTFIX:
- return expression_root->get_postfix();
- case INFIX:
- default:
- return expression_root->get_infix();
- }
+ return expression_root->get_infix();
+}
+
+std::string Expression::to_postfix_string() const
+{
+ return expression_root->get_postfix();
+}
+
+std::string Expression::to_prefix_string() const
+{
+ return expression_root->get_prefix();
}
double Expression::evaluate() const
#include <algorithm>
#include <stdexcept>
-typedef enum
-{
- PREFIX,
- POSTFIX,
- INFIX
-} StringFormat;
-
-typedef enum
-{
- ADDITION,
- SUBTRACTION,
- MULTIPLICATION,
- DIVISION,
- EXPONENT
-} Operator_types;
-
-std::map<std::string, Operator_types> operator_string_map;
-
class Expression
{
public:
Expression(Expression const&) = delete;
Expression& operator=(Expression const&) = delete;
- std::string to_string(StringFormat s_format=INFIX) const;
+ std::string to_infix_string() const;
+ std::string to_postfix_string() const;
+ std::string to_prefix_string() const;
+
double evaluate() const;
protected: