Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 用波兰语表示法计算_C++_Stack_Notation - Fatal编程技术网

C++ 用波兰语表示法计算

C++ 用波兰语表示法计算,c++,stack,notation,C++,Stack,Notation,我有以下代码: #include <iostream> #include <string> #include “stack.h” int main (int argc, char *argv[]) { char *a = argv[1]; int N = strlen(a); stack<int> polish(N); int el; for (int i = 0; i < N; i++){ if (a[i] ==

我有以下代码:

#include <iostream>
#include <string>
#include “stack.h”
int main (int argc, char *argv[]) {
   char *a = argv[1]; 
   int N = strlen(a);
   stack<int> polish(N); int el;
   for (int i = 0; i < N; i++){
      if (a[i] == '+'){
         el = polish.readStack(); polish.outofStack();
         polish.inStack( el + polish.readStack()); polish.outofStack()
      }
      if (a[i] == '*'){
         el = polish.readStack(); polish.outofStack();
         polish.inStack(el * polish.readStack()); polish.outofStack()
      }
      if ((a[i] >= '0') && (a[i] <= '9')){
         el = polish.readStack(); polish.outofStack()
         polish.inStack(10 * el + (a[i++]-'0'));
      }
   }
   cout << polish.outofStack() << endl;
}

它看起来像是一个读取和计算的算法

比如说,

1 2 3 + 4 - -
意味着

i、 e

此代码行:

polish.inStack(10 * el + (a[i++]-'0'));
应该通过追加数字来组合数字。
(a[i++]-'0')
正在从字符数字如'3'转换为整数3

最初,我们的堆栈中有一个零。 例如,如果您有“123”,它将按如下方式逐字符读取它们:

  • 阅读
    1
    。从堆栈(0)中获取最后一个数字,使
    0*10+1
    =1。把它推回堆栈

  • 阅读
    2
    。从堆栈(1)中获取最后一个数字,使
    1*10+2
    =12。推回

  • 阅读
    3
    。从堆栈(12)中获取最后一个数字,使
    12*10+3
    =123。把它推回去

  • 太好了!123号已被读取

  • 然而,这个代码示例是一堆糟糕的实践

  • 众所周知,将堆栈函数命名为
    Pop
    Push
    ,而不是
    readStack()
    inStack()
  • 堆栈结构要求在读取后删除元素
    readStack()
    不提供该选项
  • 几个
    if
    s而不是
    switch
    语句
  • 不要在循环中增加你的计数器
  • 这段代码实际上不起作用,因为它不分割值

  • 这样一个奇怪的
    堆栈实现
    。众所周知,调用方法
    push
    pop
    ,而不是
    readStack
    inStack
    。另外,
    pop
    应该自动删除最后一个元素,而不调用
    outOfStack
    。如果我错了,请纠正我,但这不应该起作用:操作的结果我们被推入堆栈(不删除第二个操作数),然后被丢弃<代码>polish.inStack(10*el+(a[i++]-'0')如果假设
    stack::readStack()
    返回一个
    int
    ,这意味着您将传递10*该调用的结果+作为
    stack::inStack()输入的下一个字符
    @YeldarKurmangaliyev看起来像是一个非标准名称的标准界面--
    inStack
    push
    readStack
    top
    outOfStack
    pop
    。通常还有
    peek
    ,它正在做
    readStack
    似乎正在做的事情。
    Add 1; add 2; add 3; sum up the last two; add 4; substract the last two; substract the last two.
    
    1 - ((2 + 3) - 4) = 0
    
    polish.inStack(10 * el + (a[i++]-'0'));