c++ - C++中前缀表达式的递归评估

标签 c++ recursion expression prefix evaluation

<分区>

我正在尝试用 C++ 编写一个递归算法,该算法计算以下类型的表达式:“运算符”、“变量”、“变量”并返回运算(示例:输入 = + 3 4;输出 = 7)。运算符只是基本的(+,-,*,/),变量是1到9之间的整数。问题是我不知道如何开始以及使用什么方法。我不能使用堆栈或列表。

编辑:我正在准备 C++ 入门考试,所以我不允许使用任何复杂的方法来解决问题,我只能使用过程、循环、递归以及搜索和线程方法。

谢谢。

最佳答案

因为您(显然)只处理二元运算符,所以这是非常微不足道的(有一个警告:虽然它不会显式使用堆栈,但几乎任何理智的递归实现都会隐式使用堆栈)。

基本模式看起来像这样:

int apply(char op, int a, int b) {
    switch (op) { 
       case '+': return a + b;
       case '-': return a - b;
       case '/': return a / b;
       case '*': return a * b;
       default: throw bad_operator(op);
    }
}   

int expression(char *&input) {
    char op = *input++;

    if (isdigit(op)) 
       return op - '0';

    int a = expression(input);
    int b = expression(input);
    return apply(op, a, b);
}

快速测试程序:

#include <ctype.h>
#include <iostream>
#include <exception>
#include <string>

struct bad_operator : public std::logic_error { 
    bad_operator(char ch)  : 
        std::logic_error(std::string("Bad operator: ") + ch) 
    {}
};

int main() {
    char *input="+/42-43";
    std::cout << expression(input);
    return 0;
}

关于c++ - C++中前缀表达式的递归评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14228868/

相关文章:

C++ 外部定义内联函数

Javascript,一个简单的递归函数

java - 原始递归偶/奇 - 它到底做了什么?

c# - 从表达式中获取父成员

python - 正则表达式格式化没有空格的url

c++ - Qt - 检查互联网连接并创建线程

c++ - 警告 : non-static data member initializers only available with -std=c++11 or -std=gnu++11 [enabled by default]

C++ 函数来截断非常小的数值

python - 有序字典的有序字典需要转换为字典的字典

go - 如何在 gval 表达式中添加引号