Last active
May 5, 2018 20:08
-
-
Save patelpreet422/cd77d84d65fe7e9dba30a094a972f89e to your computer and use it in GitHub Desktop.
Reverse Polish Notation (RPN) using C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* This code was compiled using g++-7 on Ubuntu 16.04LTS platform using following command | |
* g++-7 -std=c++17 rpn.cpp | |
* ./a.out | |
*/ | |
#include <iostream> | |
#include <vector> | |
#include <boost/algorithm/string.hpp> | |
#include <boost/lexical_cast.hpp> | |
#include <cctype> | |
inline bool is_punct(const std::string &str) | |
{ | |
if(str.length() != 1) return false; | |
return ispunct(boost::lexical_cast<char>(str)); | |
} | |
int main() | |
{ | |
std::string eval; | |
getline(std::cin, eval); | |
std::vector<std::string> tokens; | |
boost::split(tokens, eval, [](char c){return c == ' ';}); | |
std::vector<int> temps; | |
for(const auto &t: tokens){ | |
if(is_punct(t)){ | |
char op = boost::lexical_cast<char>(t); | |
int n1 = temps.back(); | |
temps.pop_back(); | |
int n2 = temps.back(); | |
temps.pop_back(); | |
switch(op){ | |
case '+': temps.push_back(n2 + n1); break; | |
case '-': temps.push_back(n2 - n1); break; | |
case '*': temps.push_back(n2 * n1); break; | |
case '/': temps.push_back(n2 / n1); break; | |
} | |
} else { | |
temps.push_back(boost::lexical_cast<int>(t)); | |
} | |
} | |
std::cout << temps.back() << '\n'; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment