| CODE |
| #include <iostream> #include <string> #include <sstream> #include <vector> #include <stack> #include <map> #include <algorithm> using namespace std; typedef double (*Op)(double, double); typedef map<string, Op> OpTable; double AddOp(double lhs, double rhs) { return lhs + rhs; } double SubOp(double lhs, double rhs) { return lhs - rhs; } double MulOp(double lhs, double rhs) { return lhs * rhs; } double DivOp(double lhs, double rhs) { return lhs / rhs; } OpTable ops; stack <double> rpn; void ParseToken(string token) { // Check if token exists in ops map OpTable::iterator op = ops.find(token); // If token is op if (op != ops.end()) { // Pop lhs & rhs values from stack double rhs = rpn.top(); rpn.pop(); double lhs = rpn.top(); rpn.pop(); // Push new value onto the stack rpn.push(op->second(lhs, rhs)); } // If token is a number else { double num; istringstream strnum(token); strnum >> num; rpn.push(num); } } int main(int argc, char * argv[]) { // Define vars string input; vector<string> tokens; // Build ops table ops["+"] = &AddOp; ops["-"] = &SubOp; ops["*"] = &MulOp; ops["/"] = &DivOp; for(;;) { // Get & validate input getline(cin, input); if (cin.fail()) break; // Tokenize tokens.clear(); istringstream inputstream(input); copy(istream_iterator<string>(inputstream), istream_iterator<string>(), back_inserter(tokens)); for_each(tokens.begin(), tokens.end(), ParseToken); // Output result & pop result from stack cout << "\t" << rpn.top() << endl; rpn.pop(); } return 0; } |