C++primer 11.3.7节练习

练习11.37

在关键字类型的元素没有明显的序关系的情况下,无序容器是非常有用的,在某些应用中,维护元素的序代价非常高昂,此事无序容器也很有用

练习11.38

单词计数程序

 1 #include <iostream>
 2 #include <fstream>
 3 #include <string>
 4 #include <sstream>
 5 #include <set>
 6 #include <map>
 7 #include <algorithm>
 8 #include <vector>
 9 #include <algorithm>
10 #include <iterator>
11 #include <unordered_map>
12 
13 using namespace std;
14 
15 
16 
17 int main()
18 {
19     unordered_map<string, size_t> words_count;
20     string word;
21     while (cin >> word)
22     {
23         ++words_count[word];
24     }
25 
26     for (auto c : words_count)
27     {
28         cout << c.first << " occurs " << c.second << endl;
29     }
30     system("pause");
31     return 0;
32 }

 

单次转换程序

 1 #include <iostream>
 2 #include <fstream>
 3 #include <string>
 4 #include <sstream>
 5 #include <set>
 6 #include <map>
 7 #include <algorithm>
 8 #include <vector>
 9 #include <algorithm>
10 #include <iterator>
11 #include <unordered_map>
12 
13 using namespace std;
14 
15 void word_transform(ifstream &map_file, ifstream &input);
16 unordered_map<string, string> buildMap(ifstream &map_file);
17 const string &transform(const string &s, const unordered_map<string, string> &m);
18 
19 int main()
20 {
21     ifstream test1("test1.txt");
22     ifstream test2("test2.txt");
23     word_transform(test1, test2);
24     system("pause");
25     return 0;
26 }
27 
28 void word_transform(ifstream &map_file, ifstream &input)
29 {
30     auto trans_map = buildMap(map_file);
31     string text;
32     while (getline(input, text))
33     {
34         istringstream stream(text);
35         string word;
36         bool firstword = true;
37         while (stream >> word)
38         {
39             if (firstword)
40                 firstword = false;
41             else
42                 cout << " ";
43             cout << transform(word, trans_map);
44         }
45         cout << endl;
46     }
47 }
48 
49 unordered_map<string, string> buildMap(ifstream & map_file)        //将文件的转换规则放在map内
50 {
51     unordered_map<string, string> tran_map;
52     string key;
53     string value;
54     while (map_file >> key && getline(map_file, value))
55     {
56         try {
57             if (value.size() > 1)
58                 tran_map[key] = value.substr(1);
59             else
60                 throw runtime_error("no rule for " + key);
61         }
62         catch (runtime_error error)
63         {
64             cout << error.what() << endl;
65         }
66     }
67     return tran_map;
68 }
69 
70 const string & transform(const string & s, const unordered_map<string, string>& m)        //将字符串按照规则进行转换
71 {
72     auto map_it = m.find(s);
73     if (map_it != m.cend())
74         return map_it->second;
75     else
76         return s;
77     // TODO: 在此处插入 return 语句
78 }

 

posted @ 2017-08-23 15:56  五月份小姐  阅读(136)  评论(0编辑  收藏  举报