Skip to content

Instantly share code, notes, and snippets.

@NigoroJr
Created August 30, 2016 11:54
Show Gist options
  • Save NigoroJr/9b3460eec457cb36dd223c1a349a4c98 to your computer and use it in GitHub Desktop.
Save NigoroJr/9b3460eec457cb36dd223c1a349a4c98 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <vector>
#include <stack>
#include <iterator>
#include <algorithm>
#include <string>
#include <unordered_map>
const std::unordered_map<char, unsigned> OPERATORS = {
{'*', 2},
{'/', 2},
{'+', 1},
{'-', 1},
};
std::string
convert_to_rpn(const std::string& in_str) {
std::string rpn_str;
std::stack<char> stk;
for (auto&& c : in_str) {
if (std::isdigit(c)) {
rpn_str.push_back(c);
}
else if (OPERATORS.count(c) != 0) {
// First on stack?
if (stk.empty()) {
stk.push(c);
continue;
}
// Token's precedence is less than or equal to that of stack's top
if (OPERATORS.at(c) <= OPERATORS.at(stk.top())) {
rpn_str.push_back(stk.top());
stk.pop();
}
// At the end of iteration push token onto operator stack
stk.push(c);
}
else {
throw std::runtime_error{"Something went wrong"};
}
}
while (!stk.empty()) {
rpn_str.push_back(stk.top());
stk.pop();
}
return rpn_str;
}
int
main(int argc, char const* argv[]) {
std::string in_str;
std::copy(std::istream_iterator<char>(std::cin),
std::istream_iterator<char>(),
std::back_inserter(in_str));
std::cout << "Input" << std::endl;
for (auto&& c : in_str) {
std::cout << c << " ";
}
std::cout << std::endl;
auto rpn_str = convert_to_rpn(in_str);
std::cout << "Reverse Polish Notation" << std::endl;
for (auto&& c : rpn_str) {
std::cout << c << " ";
}
std::cout << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment