11.37 有序版本的优势是维护了关键字的序;当关键字类型的元素没有明显的序的关系,或维护元素的序的代价很高,则应该使用无序容器;
11.37 只需将头文件和主程序中的map改为unorderd_map
#include <iostream>
#include <unordered_map>
#include <algorithm>
using namespace std;
int main()
{
unordered_map<string, size_t> word_count;
string word;
cout << "Input words: " << endl;
while (cin >> word) {
++word_count[word];
}
for (const auto &w : word_count)
cout << w.first << " occurs " << w.second
<< ((w.second > 1)? " times" : " time") << endl;
return 0;
}
11.38
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <unordered_map>
using namespace std;
unordered_map<string, string> buildMap(ifstream &map_file)
{
unordered_map<string, string> trans_map;
string key, value;
while (map_file >> key && getline(map_file, value)) {
if (value.size() > 1)
trans_map[key] = value.substr(1);
else
throw runtime_error("no rule for " + key);
}
return trans_map;
}
const string &transform(const string &s, const unordered_map<string, string> &m)
{
auto map_it = m.find(s);
if (map_it != m.cend())
return map_it->second;
else
return s;
}
void word_transform(ifstream &map_file, ifstream &input)
{
auto trans_map = buildMap(map_file);
string text;
while (getline(input, text)) {
istringstream stream(text);
string word;
bool firstword = true;
while (stream >> word) {
if (firstword)
firstword = false;
else
cout << " ";
cout << transform(word, trans_map);
}
cout << endl;
}
}
int main(int argc, char *argv[])
{
ifstream map_file(argv[1]);
ifstream text(argv[2]);
word_transform(map_file, text);
return 0;
}