题意:给出新旧两个格式为(key:value)的字典,输出前后的变化,包括增加的、减少的、仅value值发生变化三种情况。
思路:题意说key和value都可能很长,又没有前导零和负号,所以我们可以建两个map<string,string>来记录新旧字典。
三种情况我们都可以用map.find来解决。
(1)新增键:我们遍历新字典,如果在旧字典里没有找到这个key,就输出。
(2)删除键:我们遍历旧字典,如果在新字典里没有找到这个key,就输出。
(3)修改键:我们遍历旧字典,如果在新字典里有这个key,而且二者的value不等,就输出。
因为map本身也是有序的,所以按照遍历顺序输出的key自然也是有序的。
map里的find用法:
a.find(x) // 在map a 里找key为x的键,如果没找到,返回值为a.end(),否则返回这个位置的迭代器。
map<int,int> a;
map<int,int>:: iterator it;
a.clear();
a[1] = 100;
it = a.find(1); // it = a.find(7); 如果是7就输出not find , find1输出 100
if ( it != a.end() )
cout<<it->second<<endl;
else cout<<"not find "<<endl;
#include <iostream>
#include <map>
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;
int T;
char temp[109];
map<string,string> Old,New;
void init( map<string,string>& x )
{
x.clear();
gets(temp);
char *t = temp + 1;
char *k,*p;
string value,key;
while( (k = strchr(t,':')) )
{
if ( ( p = strchr(t,',') ) == 0 ) p = &t[strlen(t)-1];
key = string(t,k);
value = string(k+1,p);
x[key] = value;
t = p + 1;
}
}
/*
void out( map<string,string>& x )
{
map<string,string>:: iterator it;
for( it = x.begin(); it != x.end(); it++ )
cout<<it->first<<" : "<<it->second<<endl;
}
*/
int main()
{
cin>>T;
getchar();
while(T--)
{
init(Old);
init(New);
map<string,string>:: iterator i;
map<string,string>:: iterator j;
int num = 0;
int tot = 0;
for( i = New.begin(); i != New.end(); i++ )
{
if ( ( j = Old.find( i->first ) ) == Old.end() )
{
if ( !num ) putchar('+');
else putchar(',');
num++;
tot++;
cout<<i->first;
}
}
if ( num ) puts("");
num = 0;
for( i = Old.begin(); i != Old.end(); i++ )
{
if ( ( j = New.find( i->first ) ) == New.end() )
{
if ( !num ) putchar('-');
else putchar(',');
num++;
tot++;
cout<<i->first;
}
}
if ( num ) puts("");
num = 0;
for( i = Old.begin(); i != Old.end(); i++ )
{
if ( ( j = New.find( i->first ) ) != New.end() && (i->second != j->second ) )
{
if ( !num ) putchar('*');
else putchar(',');
num++;
tot++;
cout<<i->first;
}
}
if ( num ) puts("");
if ( !tot ) puts("No changes");
puts("");
}
return 0;
}