map练习

 1 /*
 2 编写程序统计并输出所读入的单词出现的次数
 3 
 4 */
 5 /*
 6 //代码一:---用map索引实现惊人的简练
 7 #include <iostream>
 8 #include <map>
 9 
10 using namespace std;
11 
12 int main()
13 {
14     map<string, int> word_cnt;
15     string word;
16     while(cin >> word)
17     {
18         ++word_cnt[word];//如果查找键值word不存在,那么map中就会插入键值为word的新元素,同时用值初始化或默认构造函数初始化
19         cout << "the word " << word << " appears for " << word_cnt[word] << " times." << endl;
20     }
21     system("pause");
22     return 0;
23 }
24 */
25 //代码二:----用insert实现,可减少不必要的初始化操作
26 #include <iostream>
27 #include <map>
28 #include <string>
29 #include <utility>
30 
31 using namespace std;
32 
33 int main()
34 {
35     map< string, int > word_cnt;
36     string word;
37     while(cin >> word)
38     {
39         /*
40         使用这一版本insert(map<K, V>::value_type)的插入操作将返回一个pair类型对象,一个指向该元素的map迭代器和一个bool值
41         bool值表示是否插入成功,如果原来已经存在对应的索引值,那么插入失败,返回的bool值为false,此时map容器不做任何操作,
42         对应的赋值也是无效的(亦即此时word对应的值为原来的值,不是重新赋值的1)
43         */
44         pair< map<string, int>::iterator, bool > ret = word_cnt.insert( make_pair(word, 1) );
45         if(!ret.second)//说明插入失败
46         {
47             ++ret.first->second;
48         }
49         cout << "the word " << word << " appears for " << word_cnt[word] << " times." << endl;
50     }
51     system("pause");
52     return 0;
53 }
 1 //在使用迭代器遍历map容器时,迭代器指向的元素按键的升序排列
 2 #include <iostream>
 3 #include <map>
 4 #include <utility>
 5 
 6 using namespace std;
 7 typedef map< string, int >::iterator mapitor;
 8 
 9 int main()
10 {
11     map< string, int > word_cnt;
12     string word;
13     while(cin >> word)
14     {
15         pair<mapitor, bool> ret = word_cnt.insert(make_pair(word, 1));
16         if(!ret.second)
17             ++ret.first->second;
18     }
19     for(mapitor it = word_cnt.begin(); it != word_cnt.end(); ++it)
20         cout << it->first << "    " << it->second << endl;
21     system("pause");
22     return 0;
23 }
原文地址:https://www.cnblogs.com/dongsheng/p/3311625.html