This C++ program demonstrates how to evaluate a postfix expression using a stack. Postfix, or reverse Polish notation (RPN), is a mathematical notation wherein every operator follows all of its operands. It eliminates the need for parentheses as long as the number of operands that the operator takes is fixed.
Program Code
#include <iostream> #include <stack> #include <string> #include <cctype> /** * Evaluates a postfix expression using a stack. * @param exp The postfix expression as a string. * @return The result of the evaluated expression. */ int evaluatePostfix(const std::string& exp) { std::stack<int> stack; for (char c : exp) { if (isdigit(c)) { // Push operand to stack stack.push(c - '0'); // Convert char to integer } else { // Operator encountered, pop two elements from stack int val1 = stack.top(); stack.pop(); int val2 = stack.top(); stack.pop(); // Perform operation and push result back to stack switch (c) { case '+': stack.push(val2 + val1); break; case '-': stack.push(val2 - val1); break; case '*': stack.push(val2 * val1); break; case '/': stack.push(val2 / val1); break; } } } // The result of the expression is the only element left in the stack return stack.top(); } int main() { std::string postfix = "231*+9-"; std::cout << "Postfix Expression: " << postfix << std::endl; std::cout << "Evaluated Result: " << evaluatePostfix(postfix) << std::endl; return 0; }
Function Documentation
int evaluatePostfix(const std::string& exp)
This function evaluates a given postfix expression using a stack and returns the result as an integer.
- Parameters:
exp
: A string containing the postfix expression to evaluate.
- Returns: The result of the evaluated postfix expression.
- Description:The function iterates over each character in the postfix expression. If it encounters a digit, it pushes it onto the stack after converting it from a character to an integer. If it encounters an operator, it pops the two topmost elements from the stack, performs the appropriate operation based on the operator, and pushes the result back onto the stack. The final result, which is the only element left in the stack, is returned.
Example Usage
std::string postfix = "231*+9-"; std::cout << "Postfix Expression: " << postfix << std::endl; std::cout << "Evaluated Result: " << evaluatePostfix(postfix) << std::endl;
This will output: Evaluated Result: 14