C++ Primer 第9章 习题9.43

来源:互联网 发布:罗素 作品 知乎 编辑:程序博客网 时间:2024/04/28 02:44
//9.43.cpp//使用stack对象处理带圆括号的表达式。遇到左圆括号时,将其标记下来。//然后在遇到右圆括号时,弹出stack对象中这两边括号之间的元素(包括左圆括号)//接着在stack对象中压入一个值,用以表明这个用一对圆括号括起来的表达式已经被替换。#include<iostream>#include<stack>#include<string>using namespace std;int main(){stack<char> sexp;//处理表达式的stack对象string exp;//存储表达式的string对象//读入表达式cout<<"Enter a expression:"<<endl;cin>>exp;//处理表达式string::iterator iter=exp.begin();//初始迭代器初始位置while(iter!=exp.end()){if(*iter!=')')  //读到的字符不是右圆括号sexp.push(*iter);   //标记字符else{//读到的是右圆括号,弹出元素直到栈顶为左圆括号或栈为空while(sexp.top()!='('&&!sexp.empty())sexp.pop();}if(sexp.empty())//栈为空cout<<"parentheses are not matched"<<endl;else{//栈顶为左圆括号sexp.pop();//弹出左圆括号sexp.push('@');//表明圆括号的表达式已经被替换}++iter;}return 0;}

原创粉丝点击