水果
夏天来了 ~好开心啊,呵呵,好多好多水果
Joe经营着一个不大的水果店.他认为生存之道就是经营最受顾客欢迎的水果.现在他想要一份水果销售情况的明细表,这样Joe就可以很容易掌握所有水果的销售情况了.
Input
第一行正整数N(0<N<=10)表示有N组测试数据.
每组测试数据的第一行是一个整数M(0<M<=100),表示工有M次成功的交易.其后有M行数据,每行表示一次交易,由水果名称(小写字母组成,长度不超过80),水果产地(小写字母组成,长度不超过80)和交易的水果数目(正整数,不超过100)组成.
Output
对于每一组测试数据,请你输出一份排版格式正确(请分析样本输出)的水果销售情况明细表.这份明细表包括所有水果的产地,名称和销售数目的信息.水果先按产地分类,产地按字母顺序排列;同一产地的水果按照名称排序,名称按字母顺序排序.
两组测试数据之间有一个空行.最后一组测试数据之后没有空行.
Sample Input
1
5
apple shandong 3
pineapple guangdong 1
sugarcane guangdong 1
pineapple guangdong 3
pineapple guangdong 1
Sample Output
guangdong
|----pineapple(5)
|----sugarcane(1)
shandong
|----apple(3)
思路:
使用stl的map,map中嵌套一个map,<水果产地,<水果名称,水果数量> >,这样便能构造一个结构,方便代码表达。map还提供了“[ ]”运算符,使得map可以像数组一样使用。
使用迭代器按照从小到大的顺序循环遍历输出其中的元素。
附:迭代器的使用方法
map(映射): 一种包含成对数值的容器,一个值是实际数据值,另一个是用来寻找数据的关键字。一个特定的关键字只能与一个元素关联。
因为重载了**[ ]**运算符,map像是数组的“高级版”。
例如用 map<string,int>month_name 来表示“月份名字到月份编号”的映射,可以用month_name[“July”]=7 这样的方式来赋值。
题目代码如下:
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <map>
using namespace std;
int main()
{
int n,m,i;
string fruit,place;
int shu;
scanf("%d",&n);
while(n--)
{
map<string,map<string,int> >a;
map<string,map<string,int> >::iterator it;
map<string,int>::iterator ite;
scanf("%d",&m);
for(i=0;i<m;i++)
{
cin>>fruit>>place>>shu;
a[place][fruit]+=shu;
}
for(it=a.begin();it!=a.end();it++)
{
cout<<it->first<<"\n";
for(ite=it->second.begin();ite!=it->second.end();ite++)
cout<<" |----"<<ite->first<<"("<<ite->second<<")"<<"\n";
}
if(n!=0)
cout<<"\n";
}
return 0;
}