您的位置:首页 > 其它

水果(STL里的map,map尝鲜)

2019-02-21 00:03 239 查看

原题水果地址https://cn.vjudge.net/problem/34603/origin
夏天来了,好开心啊,好多好多水果~~
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)

关于map的用法,插入map里后,本身就是有序的,这道题有三个量,都知道map基本用法map<type,type>
怎么弄三个变量?
1:
可以用pair(不知的可以百度一下,相当于一个有两个量的结构体写成map<string,pair<string,int>空格>);
2:
map里面套map,写成map<string, map<string, int>空格>p; 定义的这个map名字是p;

重点:
可以先对应着我ac的代码看

说下访问map的值,我知道的有两种。感觉就这个重要。
第一种:一搜都能搜到正常的访问,对于刚才我设置的,我得写两行

map<string,map<string, int> >::iterator it;   外层的指针
map<string, int>::iterator iter;     内层的指针 然后for循环时是
访问时是这样
for(it = p.begin(); it != p.end(); it++)
for(iter = it->second.begin(); iter != it->second.end(); iter++)  这种说完了;

第二种:是c++ 11里面的auto, 这个auto可真是太强大了,也可以百度一波。这里说下如何访问

不用写那两行定义指针,直接for循环访问
for(auto it = p.begin(); it != p.end(); it++)
for(auto iter = it->second.begin(); iter != it->second.end(); iter++)  这种说完了;

这个auto就是“自动”这个单词的缩写,就是能够自动变成相应的类型。

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<map>
#include<stdlib.h>
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int n, m;
cin >> m;
while(m--)
{
string kind, locate;
int num;
map<string,map<string, int> >p;
map<string,map<string, int> >::iterator it;   //这是第一种的访问方式
map<string, int>::iterator iter;       // 第二种是这两行不要,下边it,iter前面加个auto就行。
cin >> n;
while(n--)
{
cin >> kind >> locate >> num;
p[locate][kind]+=num;
}
for(it = p.begin(); it != p.end(); it++)
{
cout << it->first << endl;
for(iter = it->second.begin(); iter != it->second.end(); iter++)
{
cout<<"   |----"<<iter->first<<"("<<iter->second<<")"<<endl;
}
}
if(m) cout << endl;
}
return 0;
}
---------------------------------“给时间以生命,而不是给生命以时间。”-------------------------------------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: