55#include < functional>
66#include < cmath>
77#include < map>
8+ #include < variant>
9+ #include < stdexcept>
810
911class MathParser {
1012public:
11- using EvaluateFunc = std::function<double (const std::vector<double >&)>;
13+ struct Token {
14+ enum class Type {
15+ OPERATOR,
16+ NUMBER,
17+ VARIABLE,
18+ CONSTANT
19+ };
20+ Type type;
21+ std::variant<double , std::string> value;
22+
23+ bool operator <(const Token& other) const {
24+ if (type != other.type )
25+ return static_cast <int >(type) < static_cast <int >(other.type );
26+
27+ switch (type) {
28+ case Type::NUMBER:
29+ return std::get<double >(value) < std::get<double >(other.value );
30+ default :
31+ return std::get<std::string>(value) < std::get<std::string>(other.value );
32+ }
33+ }
34+ };
35+ using EvaluateFunc = std::function<Token(const std::vector<Token>&)>;
1236 struct Operator {
1337 enum class Type {
1438 UNARY,
@@ -23,24 +47,30 @@ class MathParser {
2347 int operandCount;
2448 EvaluateFunc evaluate;
2549 std::string symbol;
26- };
50+ };
51+
2752private:
2853 std::unordered_map<std::string, Operator> operators;
2954 std::map<std::string, double > constants;
55+ std::map<std::string, double > variables;
3056 void init ();
3157
3258 bool isOperator (const std::string& symbol);
3359 bool isOperator (char symbol);
3460
3561 bool isConstant (const std::string& symbol);
3662
63+
64+ double evaluateRPN (const std::vector<Token>& RPN); // evaluate Reverse Polish notation
65+ std::vector<Token> toRPN (const std::string& expression); // make Reverse Polish notation
66+
3767public:
3868 MathParser ();
3969 ~MathParser () = default ;
4070
4171 void registerOperator (const std::string& symbol, Operator op);
4272 void registerConstant (const std::string& symbol, double value);
4373 double evaluate (const std::string& expression);
44- double evaluateRPN (const std::vector<std::string>& RPN); // evaluate Reverse Polish notation
45- std::vector<std::string> toRPN (const std::string& expression); // make Reverse Polish notation
74+ double tokenToDouble (const Token& token);
75+ double getVariableValue (const std::string& varName);
4676};
0 commit comments