I'm writing a function that reads a postfix expression in the form of a string and computes it accordingly.
Is there a simple way to convert the character of an arithmetic operator to the arithmetic operator itself in C++?
As @chris' comment says, you could create a map of characters to 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 throw std::bad_function_call
if you call the function with a character that doesn't represent a known operator.
It will also create unwanted entries in the map for such unknown characters, to avoid that you could make it slightly more complciated:
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);
}
(N.B. This uses C++11 features, but can pretty easily be translated to C++03, using boost::function
or std::tr1::function
)
Assuming that this is for the classic RPN programming exercise, the simplest solution is to use a switch
statement:
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With