这是一段利用栈处理括号表达式的程序:
1. 当你看到一个左括号,直接入栈;
2. 看到一个右括号,从stack总pop对象,直到遇到左括号,左括号也pop出栈。
3. 然后将一个值作为运算结果存入栈中。
题目来源于C++ Primer,给的程序如下。
问题:
1、这里有个变量seen记录了有多少个括号,但是这个seen有什么用?
2、expr这个变量,定义为什么要定义成引用?
int main()
{
auto& expr = "This is (Mooophy(awesome)((((wooooooooo))))) and (ocxs) over";
auto repl = '#';
auto seen = 0;
stack<char> stk;
for (auto c : expr) {
stk.push(c);
if (c == '(') ++seen; // open
if (seen && c == ')') { // pop elements down to the stack
while (stk.top() != '(') stk.pop();
stk.pop(); // including the open parenthesis
stk.push(repl); // push a value indicate it was replaced
--seen; // close
}
}
// Test
string output;
for (; !stk.empty(); stk.pop()) output.insert(output.begin(), stk.top());
cout << output << endl; // "This is # and # over"
}