學習 STL ,本題就是一個 str -> str -> int 的映射,要是熟悉 STL 很好做,不過很久不寫也忘記的差不多了,看了一個別人怎麼搞的,還是感覺 STL 很強,習慣了 python 就亂用 C++ ,自己寫的一堆 bug 。
那我們懂了是 str -> str -> int 的映射關係,用 map 來存儲,開個 iterator 迭代就可以了,因爲 auto 禁用,所以就用 iterator 就可以。
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
map<string,map<string,int> > fruit;
string type,place;
int num;
for(int i = 0; i < n; i ++){
cin >> type >> place >> num;
fruit[place][type] += num;
}
map<string,map<string,int> > :: iterator it;
map<string,int> :: iterator ti;
for(it = fruit.begin(); it != fruit.end(); it ++){
cout << it -> first << endl;
for (ti = it->second.begin(); ti != it->second.end(); ti ++){
cout << " |----" << ti->first << "(" << ti->second << ")" << endl;
}
}
return 0;
}
圖片源於計蒜客,侵刪。