练习11.37 一个无序容器与其有序版本相比有何优势?有序版本有何优势?
无序容器性能优秀。
有序容器可以按<运算符处理元素。
练习11.38 用unordered_map重写单词计数程序(参见11.1节,第375页)和单词转换程序(参见11.3.6节,第391页)。
//单词统计程序
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <string>
using namespace std;
int main()
{
unordered_map<string, size_t> word_count;
unordered_set<string> exclude = { "the","an","a","and","or" };
string word;
while (cin >> word) {
if (exclude.find(word) == exclude.cend()) {
++word_count[word];
}
}
for (auto &i : word_count) {
cout << i.first << " occurs " << i.second << (i.second > 1 ? "times" : "time") << endl;
}
return 0;
}
//单词转换程序。
#include <iostream>
#include <string>
#include <unordered_map>
#include <fstream>
#include <sstream>
using namespace std;
void main_func(ifstream &, ifstream&);
unordered_map<string, string> build_map(ifstream&);
const string &transform(const string &, unordered_map<string, string> &);
int main()
{
ifstream map_file("map_file.txt");
ifstream input("input.txt");
main_func(map_file,input);
}
void main_func(ifstream &map_file, ifstream&input)
{
auto trans_unordermap = build_map(map_file);
string line;
while (getline(input, line)) {
istringstream stream(line);
string word;
bool firstword = true;
while (stream >> word) {
if (firstword == true) {
firstword = false;
}
else
{
cout << " ";
}
cout << transform(word, trans_unordermap);
}
cout << endl;
}
}
unordered_map<string, string> build_map(ifstream &map_file)
{
unordered_map<string, string>change_rule;
string key;
string mapped;
while (map_file >> key && getline(map_file, mapped)) {
if (mapped.size() > 1) {
change_rule[key] = mapped.substr(1);
}
else {
throw runtime_error("no data for change " + key);
}
}
return change_rule;
}
const string &transform(const string &s, unordered_map<string, string>&m)
{
auto iter = m.find(s);
if (iter != m.cend()) {
return iter->second;
}
else {
return s;
}
}