2#include "expression_evaluation.h"
4 double evaluateExpression(
const std::map<std::string,double>& variables, std::string expression)
6 std::stack<std::string> operators;
7 std::stack<double> values;
8 std::vector<std::string> splitsContainer;
9 boost::split(splitsContainer,expression,boost::is_any_of(
" "));
10 for(uint i = 0; i < splitsContainer.size(); i++) {
11 if(existingOperators.count(splitsContainer[i])) {
12 operators.push(splitsContainer[i]);
14 else if(variables.find(splitsContainer[i]) != variables.end()) {
15 values.push(variables.at(splitsContainer[i]));
17 else if(splitsContainer[i] ==
"(") {
20 else if(splitsContainer[i] ==
")") {
21 if(operators.empty()) {
24 std::string op = operators.top();
26 double numericalV = values.top();
29 numericalV = values.top() + numericalV;
33 numericalV = values.top() - numericalV;
37 numericalV = values.top() * numericalV;
41 numericalV = values.top() / numericalV;
45 numericalV = std::pow(values.top(), numericalV);
48 else if(op ==
"max") {
49 numericalV = std::max(values.top(),numericalV);
52 else if(op ==
"min") {
53 numericalV = std::min(values.top(),numericalV);
56 else if(op ==
"sin") {
57 numericalV = std::sin(numericalV);
59 else if(op ==
"cos") {
60 numericalV = std::cos(numericalV);
62 else if(op ==
"sqrt") {
63 numericalV = std::sqrt(numericalV);
66 numericalV = std::log(numericalV);
68 values.push(numericalV);
73 numericalV = str2dbl(splitsContainer[i]);
74 values.push(numericalV);
75 }
catch(std::exception& ex) {
76 std::cerr <<
"Nešto nije u redu. Nisam mogao obraditi: " << splitsContainer[i] <<
'\n';