UVA12504 Updating a dictionary

本文介绍了一个使用C++实现的词典比对程序,通过map数据结构存储和对比两份词典文件中的词条,实现了对新增、修改和仅出现在一份词典中的词条的高效查找。文章分享了作者在调试过程中遇到的有趣问题,以及如何遍历map的技巧。

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

   这个题没有什么难的,用map进行查询即可。但是,交这个题5遍全是编译错误,而且是整整一页多的错误,找了一小时bug最后把变量名time改成times就过了,不知为什么,难道用time作变量名不行吗?

   通过这题还学到了遍历map的方法,收获还是不小的。

 

#include<iostream>
#include<map>
#include<cstring>
#include<string>
#include<vector>
#include<cstdio>
#include<sstream>
#include<algorithm>
const int maxn = 100 + 20;
using namespace std;
const char fu[3] = {'+','-','*'};
map<string,string>value;//存储单词及对应的键值
map<string,int>times;   //存储单词在两个词典中出现的总次数(1或2)
vector<string>out[3];   //三个数组分别表示+,-,*。
void trans(string &s)
{
    for(int i = 0; i < s.length(); i++)
    if(s[i] == '{' || s[i] == ',' || s[i] == '}') s[i] = ' '; //用stringstream读取,把无关的字符都换成空格
}
void solve(string s, int t)
{
    stringstream ss(s);
    string x;
    while(ss >> x){
        int k = x.find(':');  //提取单词及键值
        string s1 = x.substr(0,k);  
        string s2 = x.substr(k+1);
        if(t == 1){
            value[s1] = s2;
            times[s1] = 1;
        }
        if(t == 2){
            if(!value.count(s1))out[0].push_back(s1);
            else{
                if(value[s1] != s2) out[2].push_back(s1);
                times[s1] = 2;
            }
        }
    }
}
int main()
{
    int T;
    cin >> T;
    string s1,s2;
    while(T--){
        cin >> s1 >> s2;
        trans(s1);trans(s2);
        value.clear();
        times.clear();
        for(int i = 0; i < 3; i++) out[i].clear();
        solve(s1,1); 
        solve(s2,2);
        map<string,int>::iterator it; 
        for(it = times.begin(); it != times.end(); ++it)  //遍历map
           if(it->second == 1) out[1].push_back(it->first);
        for(int i = 0; i < 3; i++) sort(out[i].begin(),out[i].end());
        int change = 0;
        for(int i = 0; i < 3; i++){
            if(out[i].empty()) continue;
            change = 1;
            cout << fu[i] << out[i][0];
            for(int j = 1; j < out[i].size(); j++)
                cout << ',' << out[i][j];
            cout << '\n';
        }
        if(!change) cout << "No changes\n\n";
        else cout << '\n';
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值