c++primer习题9.43

来源:互联网 发布:dota2淘宝店 编辑:程序博客网 时间:2024/06/03 00:01

使用 stack 对象处理带圆括号的表达式。遇到左圆括号
时,将其标记下来。然后在遇到右加括号时,弹出 stack
对象中这两边括号之间的相关元素(包括左圆括号)。
接着在 stack 对象中压入一个值,用以表明这个用一对
圆括号括起来的表达式已经被替换。

类似括号匹配

#include <iostream>#include <string>#include <stack>using namespace std;int main(){    string str;    cin >> str;    stack<char> stk;    for(string::iterator iter = str.begin(); iter != str.end(); ++iter)    {        if(*iter != ')')    //没遇到 ')' ,压栈            stk.push(*iter);        else            {                while(stk.top() != '(' && !str.empty())                    stk.pop();                      //遇到')',弹栈至 '('处                if(stk.empty())                    cout << "括号不匹配" << endl;                else                    {                        stk.pop();  //弹出左括号                        stk.push('_'); //'_'替代括号内容                    }            }    }    //正序输出    stack<char> stk1;    while(!stk.empty())    {        stk1.push(stk.top());        stk.pop();    }    while(!stk1.empty())    {        cout << stk1.top();        stk1.pop();    }    return 0;}

输入示例:
hi(1)i’m(22)apple(333),./;’

0 0