C++ //练习 11.38 用unordered_map重写单词计数程序(参见11.1节,第375页)和单词转换程序(参见11.3.6节,第391页)。
C++ Primer(第5版) 练习 11.38
练习 11.38 用unordered_map重写单词计数程序(参见11.1节,第375页)和单词转换程序(参见11.3.6节,第391页)。
环境:Linux Ubuntu(云服务器)
工具:vim
代码块
单词计数程序
/*************************************************************************> File Name: ex11.38a.cpp> Author: > Mail: > Created Time: Mon 08 Apr 2024 09:42:21 AM CST************************************************************************/#include<iostream>
#include<iomanip>
#include<string>
#include<map>
#include<unordered_map>
#include<vector>
using namespace std;int main(){unordered_map<string, size_t> wordCount;string word;cout<<"Enter words: ";while(cin>>word){++wordCount.insert({word, 0}).first->second;if(cin.get() == '\n'){break;}}cout<<"Word Count: "<<endl;for(const auto &w : wordCount){cout<<"Word: "<<setw(8)<<left<<w.first<<" Count: "<<w.second<<endl;}return 0;
}
运行结果显示如下
单词转换程序
/*************************************************************************> File Name: ex11.38b.cpp> Author: > Mail: > Created Time: Mon 08 Apr 2024 09:00:00 AM CST************************************************************************/#include<iostream>
#include<fstream>
#include<sstream>
#include<string>
#include<map>
#include<unordered_map>
#include<iterator>
using namespace std;unordered_map<string, string> buildMap(ifstream &map_file){unordered_map<string, string> map;string key;string value;while(map_file>>key && getline(map_file, value)){if(value.size() > 1){map[key] = value.substr(1);}else{throw runtime_error("no rule for " + key);} }return map;
}const string &transform(const string &s, const unordered_map<string, string> &m){auto it = m.find(s);if(it != m.cend()){return it->second;}else{return s;}
}void txtTransform(ifstream &map_file, ifstream &input){auto map = buildMap(map_file);string txt;while(getline(input, txt)){istringstream stream(txt);string word;bool nonspace = true;while(stream>>word){if(nonspace){nonspace = false;}else{cout<<" ";}cout<<transform(word, map);}cout<<endl;}
}int main(){ifstream map_file("map_file.txt");ifstream input("input.txt");txtTransform(map_file, input);return 0;
}