Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one convert '+' to +, '*' to *, etc

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++?

like image 384
Derek W Avatar asked Dec 01 '22 22:12

Derek W


2 Answers

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)

like image 187
Jonathan Wakely Avatar answered Dec 05 '22 07:12

Jonathan Wakely


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;
}
like image 28
Sergey Kalinichenko Avatar answered Dec 05 '22 05:12

Sergey Kalinichenko