题目大意:有n个人,给出每个人的国籍,统计每个国家的人数。
用map<string, int>做的。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <cstdio> 2 #include <iostream> 3 #include <map> 4 #include <string> 5 #include <algorithm> 6 using namespace std; 7 #define MAXN 2000+10 8 9 map<string, int> m; 10 string str[MAXN]; 11 12 int main() 13 { 14 #ifdef LOCAL 15 freopen("in", "r", stdin); 16 #endif 17 int n; 18 scanf("%d", &n); 19 getchar(); 20 char s1[80], s2[80]; 21 m.clear(); 22 map<string, int>::iterator it; 23 while (n--) 24 { 25 gets(s1); 26 sscanf(s1, "%s", s2); 27 string t = s2; 28 it = m.find(t); 29 if (it != m.end()) m[t]++; 30 else m[t] = 1; 31 } 32 int p = 0; 33 for (it = m.begin(); it != m.end(); it++) 34 str[p++] = it->first; 35 sort(str, str+p); 36 for (int i = 0; i < p; i++) 37 cout << str[i] << " " << m[str[i]] << endl; 38 return 0; 39 }
当时就是大概看了看别人写的map用法的代码就开始写了,今天又看了看书,发现其实当时写的挺麻烦的:增加数据只用m[key]++;就足够了,而按字典序输出...根本就不用的,在map内部默认就是按key的升序进行排列的,直接输出就好了,想当初为这个纠结的啊...
不过我觉得这种学习方式还是不错的,够直观,有问题就去找资料,学习然后改正,能从中发现乐趣并可以获得一点成就感,相对于系统地看一遍书,书中直接告诉你如何如何,我现在更喜欢这种方式,毕竟我一直有着“只学现在的我感觉能用到的东西”这种“临时抱佛脚”的想法。
@2013-09-01