UVA Updating a Dictionary

xiaoxiao2021-02-28  36

#include <cstdio> #include <string> #include <map> #include<sstream> #include <cmath> #include <iostream> #include <cstring> using namespace std; char record[109]; void build(map<string,string>&x)//建立字典函数 { x.clear(); scanf("%s", record); char *t, *p, *k;//指针记录字符串,记录表示字符串,p用来控制读取字符串的结束 t = record + 1;//字符串名表示字符串首地址 string key, value;//key与value值注意相互对应 while (k=strchr(t,':')) { if ((p = strchr(t, ',')) == 0)//检验字符串是否结束 p = &t[strlen(t)-1];//最后一个元素的地址,控制字符串读取的结束 key = string(t, k);//t代表元素首地址 value = string(k + 1, p);//key与value值可能很大,注意读取时控制 x[key] = value; t = p + 1; } } int main() { int t; cin >> t; getchar(); while (t--) { map<string, string>od, nw;//新旧字典存储 build(od); build(nw); int num = 0,total=0; map<string, string>::iterator i, j;//迭代器寻找相应元素 for (i = nw.begin(); i != nw.end(); i++) { if ((j = od.find(i->first)) == od.end())//first代表key值,注意寻找旧字典中是否存在 { if (!num)//初始情况,无增添词语时 printf("+"); else//注意每个词语单独输出 printf(","); num++; total++; cout << i->first; } } if (num)//存在词语输出 printf("\n"); num = 0; for (j = od.begin(); j != od.end(); j++)//旧字典中存在的词语新字典中无则说明删去 { if ((i = nw.find(j->first)) == nw.end()) { if (!num) printf("-"); else printf(","); num++; total++; cout << j->first; } } if(num) printf("\n"); num = 0;//第三种情况,key值存在,value值改变 for (i = nw.begin(); i != nw.end(); i++) { if ((j = od.find(i->first)) != od.end() && j->second != i->second)//注意value值改变,注意相应的变化 { if (!num) printf("*"); else printf(","); num++; total++; cout << i->first; } } if(num) printf("\n"); if (total == 0) printf("No changes\n"); printf("\n");//输出格式注意仔细读题 } }

1、学到了strchr函数的用法,寻找字符串中某一元素的位置,细节易错点:注意读取key与value值时,注意指针位置的控制,数组名代表该字符串的首地址,string函数的用法,按照起始与终末位置提取字符串,同样注意提取字符位置的控制 2、三种操作的询问方法,迭代器的使用,按新字典查找还是按照旧字典查找注意区分清楚

3、map中key值与value值分别对应first与second 4、此题关键在于key值与value的读取问题,注意指针的使用
转载请注明原文地址: https://www.6miu.com/read-2628111.html

最新回复(0)