// // is_balanced returns true if the string expression contains // balanced parentheses and false otherwise. // // It demonstrates one way to use a stack, in this case, to keep // track of left parentheses that have been seen in order to match // them to right parentheses. // bool is_balanced(const string& expression) { const char LEFT_PARENTHESIS = '('; const char RIGHT_PARENTHESIS = ')'; stack store; string::size_type i; char next; bool failed = false; for (i = 0; !failed && (i < expression.length()); i++) { next = expression[i]; if (next == LEFT_PARENTHESIS) store.push(next); else if ((next == RIGHT_PARENTHESIS) && (!store.empty())) store.pop(); else if ((next == RIGHT_PARENTHESIS) && (store.empty())) failed = true; } return (store.empty() && !failed); }