C++代码实现逆波兰式

 更新时间:2020年11月01日 10:18:23   作者:ronnie88597  
这篇文章主要为大家详细介绍了C++代码实现逆波兰式,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

100行以内C++代码实现逆波兰式

逆波兰式(Reverse Polish notation,RPN,或逆波兰记法),也叫后缀表达式(将运算符写在操作数之后)。

算术表达式转逆波兰式例子:

逆波兰式整体的算法流程图如下:

下面给出我基于C++ 语言对逆波兰式算法的实现代码,值得注意的是:

1、算法中对操作数,仅支持一个字符的字母或数字的操作数,如:x,y,j,k,3,7等;如果要支持多个字符的操作数,如:var1,3.14等。需要读者自己扩展对算术表达式操作数的分词部分的代码。

2、为了为了增加转换后的逆波兰表达式的可读性,我在每个操作数和操作符输出时后面追加了一个空格。

代码如下:

/// file: ReversePolishNotation.h
#include <string>
#include <stack>

class ReversePolishNotation {
private:
 std::string _expr;
 unsigned _idx;
 std::stack<std::string> _stk;
public:
 ReversePolishNotation(const std::string &expr);

 std::string nextWord();

 std::string operator()();

 static int getOpPriority(const std::string &word);

 bool isWord(const std::string &word);

 bool isOperator(const std::string &word);
};
/// file: ReversePolishNotation.cpp
#include <iostream>
#include <cassert>
#include "ReversePolishNotation.h"
#include <cctype>
#include <sstream>

using std::cout;
using std::endl;

ReversePolishNotation::ReversePolishNotation(
 const std::string &expr) : _idx(0), _expr(expr) {}

std::string ReversePolishNotation::nextWord() {
 if (_idx >= _expr.length()) {
 return "";
 }
 return _expr.substr(_idx++, 1);
}

std::string ReversePolishNotation::operator()() {
 std::stringstream outExpr;
 std::string word;
 std::string topElem;
 while (true) {
 word = nextWord();
 if (isWord(word)) {
 outExpr << word << " ";
 } else if (isOperator(word)) {
 if (_stk.empty() || _stk.top() == "(") {
 _stk.push(word);
 continue;
 }
 topElem = _stk.top();
 while (getOpPriority(topElem) > getOpPriority(word)) {
 outExpr << topElem << " ";
 _stk.pop();
 if (_stk.empty()) {
  break;
 }
 topElem = _stk.top();
 }
 _stk.push(word);

 } else if (word == "(") {
 _stk.push(word);
 } else if (word == ")") {
 while (true) {
 topElem = _stk.top();
 _stk.pop();
 if (topElem == "(") {
  break;
 }
 assert(!_stk.empty() && "[E]Expr error. Missing '('.");
 outExpr << topElem << " ";
 }
 } else if (word == "") {
 while (!_stk.empty()) {
 topElem = _stk.top();
 assert (topElem != "(" && "[E]Expr error. Redundant '('.");
 outExpr << topElem << " ";
 _stk.pop();
 }
 break;
 } else {
 assert(false && "[W]>>>Can not recognize this word");
 }
 }
 return outExpr.str();
}

int ReversePolishNotation::getOpPriority(const std::string &word) {
 if (word == "+") { return 1; }
 if (word == "-") { return 1; }
 if (word == "*") { return 2; }
 if (word == "/") { return 2; }
 return 0;
}

bool ReversePolishNotation::isWord(const std::string &word) {
 return isalpha(word.c_str()[0]) || isdigit(word.c_str()[0]);
}

bool ReversePolishNotation::isOperator(const std::string &word) {
 return word == "+" ||
  word == "-" ||
  word == "*" ||
  word == "/";
}

/// ---测试代码---
int main() {
 assert(ReversePolishNotation("a+b*c")() == "a b c * + ");
 assert(ReversePolishNotation("(a+b)*c-(a+b)/e")() == "a b + c * a b + e / - ");
 assert(ReversePolishNotation("3*(2-(5+1))")() == "3 2 5 1 + - * ");
// assert(ReversePolishNotation("3*((2-(5+1))")() == "3 2 5 1 + - * "); // Failed Case: Redundant '('
// assert(ReversePolishNotation("3*(?2-(5+1))")() == "3 2 5 1 + - * "); // Failed Case: Can not recognize '?'
 return 0;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • QT实现QML侧边导航栏的最简方法

    QT实现QML侧边导航栏的最简方法

    本文主要介绍了QT实现QML侧边导航栏的最简方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2022-06-06
  • C++ explicit关键字的应用方法详细讲解

    C++ explicit关键字的应用方法详细讲解

    C++ explicit关键字用来修饰类的构造函数,表明该构造函数是显式的,既然有"显式"那么必然就有"隐式",那么什么是显示而什么又是隐式的呢?下面就让我们一起来看看这方面的知识吧
    2013-09-09
  • C语言实现文件读写功能流程

    C语言实现文件读写功能流程

    这篇文章主要介绍了C语言实现文件读写,文件是一段数据的集合,这些数据可以是有规则的,也可以是无序的集合。在stdio.h有一个非常重要的东西,文件指针,每个文件都会在内存中开辟一块空间,用于存放文件的相关信息
    2022-12-12
  • C语言实例讲解四大循环语句的使用

    C语言实例讲解四大循环语句的使用

    C语言有四大循环语句,他们之间可以进行任意转换。本文将首先对其语法进行讲解,然后通过一个实例用四种循环来实现。相信通过本文的学习,大家都能够对C语言循环语句有着熟练的掌握
    2022-05-05
  • C++的友元和内部类你了解吗

    C++的友元和内部类你了解吗

    这篇文章主要为大家介绍了C++的友元和内部类,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2022-01-01
  • C语言中结构体实例解析

    C语言中结构体实例解析

    大家好,本篇文章主要讲的是C语言中结构体实例解析,感兴趣的同学赶快来看一看吧,对你有帮助的话记得收藏一下
    2022-02-02
  • 详解C++中vector的理解以及模拟实现

    详解C++中vector的理解以及模拟实现

    vector是表示可变大小数组的序列容器。这篇文章主要为大家详细介绍了vector的理解以及模拟实现,文中的示例代码讲解详细,感兴趣的可以了解一下
    2023-03-03
  • 浅谈C++模板元编程

    浅谈C++模板元编程

    本篇文章主要介绍了浅谈C++模板元编程,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-12-12
  • C++中String类的常用接口函数总结

    C++中String类的常用接口函数总结

    这篇文章主要介绍了C++中Stirng类的常用接口函数,文中有详细的代码示例供大家参考,对我们学习C++有一定的帮助,感兴趣的同学可以跟着小编一起来学习
    2023-06-06
  • 深入理解c语言数组

    深入理解c语言数组

    这篇文章主要介绍了c语言数组,有需要的朋友可以参考一下
    2013-12-12

最新评论