How to convert '+' to +, '*' to * etc.

I am writing a function that reads a postfix expression as a string and evaluates it accordingly.

Is there an easy way to convert the character of an arithmetic operator to the arithmetic operator itself in C ++?

+4
source share
2 answers

Assuming this is for classic RPN programming, the easiest solution is to use the switch :

 char op = ... int lhs = ... int rhs = ... int res = 0; switch(op) { case '+': res = lhs + rhs; break; case '-': res = lhs - rhs; break; case '*': res = lhs * rhs; break; case '/': res = lhs / rhs; break; case '%': res = lhs % rhs; break; } 
+9
source

As @chris commented, you can create a character map for functors:

 std::map<char, std::function<double(double,double)> operators{ { '+', std::plus<double>{} }, { '-', std::minus<double>{} }, { '*', std::multiplies<double>{} }, { '/', std::divides<double>{} } }; double apply(double lhs, double rhs, char op) { return operators[op](lhs, rhs); } 

This will call std::bad_function_call if you call the function with a character that is not a known statement.

It will also create unwanted map entries for such unknown characters in order to avoid minor glitches:

 double apply(double lhs, double rhs, char op) { auto iter = operators.find(op); if (iter == operators.end()) throw std::bad_function_call(); return (*iter)(lhs, rhs); } 

(NB This takes advantage of C ++ 11, but it can be easily translated to C ++ 03 using boost::function or std::tr1::function )

+10
source

Source: https://habr.com/ru/post/1442557/


All Articles