如何将'+'转换为+,'*'转换为*等

Der*_*k W 4 c++ parsing postfix-notation

我正在编写一个函数,以字符串的形式读取后缀表达式并相应地计算它.

有没有一种简单的方法可以将算术运算符的字符转换为C++中的算术运算符本身?

Jon*_*ely 10

正如@chris的评论所说,你可以为仿函数创建一个角色地图:

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);
}
Run Code Online (Sandbox Code Playgroud)

std::bad_function_call如果使用不代表已知运算符的字符调用函数,则抛出此异常.

它还会在地图中为这些未知字符创建不需要的条目,以避免您可以使其稍微复杂化:

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);
}
Run Code Online (Sandbox Code Playgroud)

(注意,这使用了C++ 11的功能,但很容易被翻译成C++ 03,使用boost::functionstd::tr1::function)


das*_*ght 9

假设这是经典的RPN编程练习,最简单的解决方案是使用一个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;
}
Run Code Online (Sandbox Code Playgroud)

  • @DerekW:不,C++不包括(在标准中)任何类型的表达式求值程序.C++中的运算符由编译器解析,并且在运行时没有它们的概念. (7认同)