zoukankan      html  css  js  c++  java
  • uva 327 Evaluating Simple C Expressions 简易C表达式计算 stl模拟

    由于没有括号,只有+,-,++,--,优先级简单,所以处理起来很简单。

    题目要求计算表达式的值以及涉及到的变量的值。

    我这题使用stl的string进行实现,随便进行练手,用string的erase删掉全部空格,然后对++、--进行处理然后删去,最后就只剩简单式子了,简单循环下就出来了。

    这里有几个坑点:

    1.erase函数删除字符后,后面字符的下标都会发生变化,刚开始使用i++去检查空格,结果删除后会跳掉字符。

    2.++、--的后缀处理要注意,我开了两个数组放后缀运算的。

    3.输出的变量值是当前后自增后的数。


    唉,我发现我每次写stl,代码都很乱哪,果然缺欠练习呢。

    代码:

    #include <iostream>
    #include <string>
    using namespace std;
    
    int v[27], used[27];
    int p[27], m[27];			//record the i++ i--
    
    int main() {
    	string str;
    	while (getline(cin, str) != NULL) {
    		cout << "Expression: " << str << endl;
    		int value = 0;
    		for (int i = 0; i < 26; i++)
    			v[i] = i + 1, used[i] = p[i] = m[i] = 0;
    		for (int i = 0; i < str.size();)
    			if (str[i] == ' ')
    				str.erase(i, 1);
    			else
    				i++;
    		size_t f1, f2;
    		while (1) {
    			f1 = str.find("++");
    			if (f1 != string::npos) {
    				if (str[f1 - 1] >= 'a' && str[f1 - 1] <= 'z')
    					p[str[f1 -1] - 'a']++;
    				else
    					v[str[f1 + 2] - 'a']++;
    				str.erase(f1, 2);
    			}
    //			cout << str << endl;
    			f2 = str.find("--");
    			if (f2 != string::npos) {
    				if (str[f2 - 1] >= 'a' && str[f2 - 1] <= 'z')
    					m[str[f2 -1] - 'a']--;
    				else
    					v[str[f2 + 2] - 'a']--;
    				str.erase(f2, 2);
    			}
    			if (f1 == string::npos && f2 == string::npos)
    				break;
    //			cout << str << endl;
    		}//while
    //		cout << value << endl;
    		value += v[str[0] - 'a'];
    		used[str[0] - 'a'] = 1;
    		for (int i = 1; i < str.size(); i++) {
    			if (str[i++] == '+')
    				value += v[str[i] - 'a'], used[str[i] - 'a'] = 1;
    			else
    				value -= v[str[i] - 'a'], used[str[i] - 'a'] = 1;	
    //		cout << str[i-1] << str[i]<<' ' << value << endl;
    		}//for
    		cout << "    value = " << value << endl;
    		for (int i = 0; i < 26; i++)
    			if (used[i])
    				cout << "    " << char('a' + i) << " = "<< v[i] + p[i] + m[i] << endl;
    	}//while
    	return 0;
    }


  • 相关阅读:
    MongoDB学习总结(二) —— 基本操作命令(增删改查)
    C#连接SQLite数据库方法
    第一章 算法在计算中的作用
    VS2010学习笔记
    centos+docker+jenkins
    git一些简单运用
    centos7 cannot find a valid baseurl for repo
    https://mirrors.ustc.edu.cn/dockerce/linux/centos/dockerce/repodata/repomd.xml:HTTPS Error 404 Not Found
    python路径相关处理
    python的excel处理之openpyxl
  • 原文地址:https://www.cnblogs.com/java20130723/p/3212225.html
Copyright © 2011-2022 走看看