练习11.37:
无序容器不用关注关键字的顺序,不需要去维护元素的序,比较简单,在关键字类型的元素没有明显的序关系的情况下,无序容器更有用
有序容器在对关键字顺序有要求的情况下,性能更好
练习11.38:
重写单词计数程序:基本没区别,将map换为unordered_ma即可
#include <iostream>
using namespace std;
#include <map>
#include <string>
#include <set>
#include <unordered_map>
int main()
{
unordered_map<string, size_t>word_count;
string word;
int i = 10;
//输入十对单词-计数器对
while (i != 0 && cin >> word)
{
++word_count[word];
--i;
}
for (const auto& w : word_count)
{
cout << w.first << " occurs " << w.second << ((w.second > 1) ? " times " : " time") << endl;
}
system("pause");
return 0;
}
重写单词转换程序:将map换为unordered_ma即可
#include <iostream>
using namespace std;
#include <map>
#include <unordered_map>
#include <string>
#include <set>
#include <vector>
#include <string>
#include <fstream>
#include <sstream>
const string& transform(const string& s, unordered_map<string, string>& mp_trans)
{
auto it = mp_trans.find(s);
if (it != mp_trans.end())
{
//在单词转换规则中,转换后返回
return it->second;
}
else
{
//没有在单词转换规则中,s不变
return s;
}
}
unordered_map<string, string> buildMap(ifstream& ifst_trans)
{
unordered_map<string, string>trans_map;
string value, key, trans_value;
while (ifst_trans >> key && getline(ifst_trans, value))
{
//这里value.size() > 1是geiline除了读入空格还读入了其他
if (value.size() > 1)
{
trans_value = value.substr(1);
trans_map.insert(pair<string, string>(key, trans_value));
}
else
{
throw runtime_error("no rule for " + key);
}
}
return trans_map;
}
void word_transform(ifstream& ifst_trans, ifstream& ifst_input)
{
auto trans_map = buildMap(ifst_trans);
string text;
//按行读取打印
while (getline(ifst_input, text))
{
istringstream istr(text);
string word;
bool firstword = true;
//每一个单词结束后需要打印空格
while (istr >> word)
{
if (firstword)
{
firstword = false;
}
else
{
cout << " ";
}
cout << transform(word, trans_map);
}
cout << endl;
}
}
int main()
{
ifstream ifst_trans("regular.txt");
ifstream ifst_input("transform.txt");
word_transform(ifst_trans, ifst_input);
system("pause");
return 0;
}