4

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

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Derek W
  • 9,708
  • 5
  • 58
  • 67

2 Answers2

10

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)

Jonathan Wakely
  • 166,810
  • 27
  • 341
  • 521
9

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;
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Thank you very much for the help. I wanted to make sure that there was no arithmetic casting already available in the language. – Derek W Oct 28 '12 at 00:42
  • 7
    @DerekW: No, C++ doesn't include (in the standard) any sort of expression evaluator. Operators in C++ are resolved by the compiler, and at runtime there is no concept of them. – Ben Voigt Oct 28 '12 at 00:44