【问题标题】:Prefix(polish) notation - evaluation c++前缀(抛光)表示法 - 评估 c++
【发布时间】:2012-08-18 23:55:17
【问题描述】:

我正在寻找使用递归解析前缀表达式的代码。主要是 C++,但也可以是其他语言,我会翻译。谢谢。

【问题讨论】:

    标签: c++ prefix


    【解决方案1】:

    自己动手真的很容易(您只需要一个用于操作符的堆栈(有时/可选地是它的第一个术语))。

    但如果你真的不想做太多工作,这里有一个链接:

    prefix notation string to int conversion

    如果你需要使用递归,你基本上使用函数中的局部变量作为堆栈中的单个元素。

    例如。伪 C++ 代码如下:

    int naughtyglobalendindex = 0;
    int parse(string str) {
    
      if (/* str starts off with an integer */) return the integer;
    
      char operator;
      operator = ?? // you will need to get the first op here. Maybe sscanf(str,"%c",&operator) or similar
    
      // get first argument
      int first = parse(/* str with 1st operator removed */);
      // get 2nd integer argument
      int second = parse(/* str - get substring from naughtyglobalendindex to end*/)
    
      // return first operator second <- this is pseudocode
      // in effect you want a switch clause
      switch (operator) {
        case '+': return first + second;
        case '-': return first - second; // and so on
      }
    }
    

    您可以将伪代码转换为实际的 C++,如果需要,可以修复全局 naughtyglobalendindex 变量。

    【讨论】:

    • 但我问的是递归而不是迭代方式。这就是我问的原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-16
    相关资源
    最近更新 更多