|
发表于 2022-10-15 16:06:41
|
显示全部楼层
本楼为最佳答案
本帖最后由 dolly_yos2 于 2022-10-15 16:10 编辑
可以测试一下看看是不是这个意思(总觉得写复杂了)(假设操作数总在 int 范围内、输入总是以操作数开始、除最后一个操作数外每个操作数后总是紧接着一个四则运算符、每个四则运算符后总是紧接着一个操作数、输入中没有任何其他符号)
- #include <iostream>
- #include <vector>
- void parse_helper(
- const std::vector<int>& operands,
- const std::vector<char>& operators,
- const size_t level,
- std::ostream& output
- ){
- bool issue_parentheses = false;
- if(level > 0){
- if(!(operators.at(level) & 4u) && (operators.at(level - 1) & 4u)){
- issue_parentheses = true;
- output.put('(');
- }
- parse_helper(operands, operators, level - 1, output);
- }else{
- output << operands.at(0);
- }
- if(issue_parentheses) output.put(')');
- output.put(operators.at(level) - 1);
- output << operands.at(level + 1);
- }
- void parse(std::istream& input, std::ostream& output){
- std::vector<int> operands;
- std::vector<char> operators;
- int value;
- char op;
- input >> value;
- operands.emplace_back(value);
- while(true){
- input >> op >> value;
- if(input.eof()) break;
- operands.emplace_back(value);
- operators.emplace_back(op + 1); // 一个小小的 trick 来简化算符优先级判断
- // 考虑到 ASCII 下四则运算符的码值分别为
- // * -- 0x2A (00101010)
- // + -- 0x2B (00101011)
- // - -- 0x2D (00101101)
- // / -- 0x2F (00101111)
- // 给码值加一后可见高优先级运算符的第三低有效位(从一开始)
- // 均为 0 而低优先级的均为 1
- }
- parse_helper(operands, operators, operators.size() - 1, output);
- }
- int main(){
- parse(std::cin, std::cout);
- return 0;
- }
复制代码 |
评分
-
查看全部评分
|