前缀(波兰)符号 - 评估c ++ [英] Prefix(polish) notation - evaluation c++

查看:127
本文介绍了前缀(波兰)符号 - 评估c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am looking for code wchich parses prefix expressions using recursion. Primarily in C++, but it can bee in other language, i will translate. Thanks.

推荐答案

这很容易做自己(你只需要一个堆栈为运算符))。

It's really easy to do yourself (you just need a stack for the operators (and sometimes/optionally its first term)).

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

But if you really don't want to do much work, here's a link:

前缀符号字符串到int转换

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

If you need to use recursion, you basically use local variables in the function as individual elements in your stack.

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

Eg. pseudo-C++ code follows:

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 变量。

You can convert the pseudocode to actual C++, and if you want, fix the global naughtyglobalendindex variable if you want.

这篇关于前缀(波兰)符号 - 评估c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆