C++ Acwing每日一题(春季)零散笔记

本文介绍了C++中const关键字的使用,auto类型推断,以及std::vector迭代器的简化用法。重点讲解了中缀表达式的解析算法,涉及栈、优先级计算和计算过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. const=constant 常量

const int maxn=1e4+50; //声明maxn变量只有可读性

2. auto 根据后面的值推测自己的值是什么   

注意事项

std::vector<std::string> ve;
std::vector<std::string>::iterator it = ve.begin();
//第二句可换成
auto it = ve.begin();

3.for(auto c:s)与for(auto &c:s)的区别  后者可以更新s中的值

     string  s( "hello world" );
     for (auto c:s)
     c= 't' ;
     cout<<s<<endl; //结果为hello world
     for (auto &c:s)
     c= 't' ;
     cout<<s<<endl;  //结果为ttttttttttt

3.中缀表达式,板子

#include<iostream>
#include<string>
#include<algorithm>
#include<stack>
#include<unordered_map>

using namespace std;

stack<int> num;
stack<char> op;

//如果op含有^   增加{'^',3}  依次类推,数字越大优先级越高
unordered_map<char,int> h{{'+',1},{'-',1},{'*',2},{'/',2}};

void eval(){ //取出num栈顶的两个数并计算
    int b=num.top(); num.pop();
    int a=num.top(); num.pop();
    char p=op.top(); op.pop();

    int sum=0;
    if(p=='+') sum=a+b;
    else if(p=='-') sum=a-b;
    else if(p=='*') sum=a*b;
    else sum=a/b;

    num.push(sum);
}

int main(){
    string s;
    cin>>s;
    for(int i=0;i<s.size();i++){
        if(isdigit(s[i])){ //s[i]是数字
            int x=0,j=i;
            while(j<s.size()&&isdigit(s[j])){
                x=x*10+s[j++]-'0';
            }
            i=j-1;
            num.push(x);
        }else if(s[i]=='(') op.push(s[i]);
        else if(s[i]==')'){
            while(op.top()!='(') eval();
            op.pop();
        }else{ 
            while(op.size() && h[op.top()]>=h[s[i]]) eval(); //当前运算符级别小于op栈顶运算符级别
            op.push(s[i]);
        }
    }
    while(op.size()) eval();
    cout<<num.top()<<endl;
    return 0;
}

 

 

 

 

 

 

持续更新中。。。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值