练习 11.33:实现你自己版本的单词转换程序。
练习 11.34:如果你将transform函数中的find替换为下标运算符,会发生什么情况?
练习 11.35:在buildMap中,如果进行如下改写,会有什么效果?
trans_map[key] = value.substr(1);
改为trans_map.insert({key, value.substr(1)})
#include <iostream>
#include <fstream>
#include <sstream>
#include <map>
#include <stdexcept>
using namespace std;
map<string, string> buildMap(ifstream &map_file)
{
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);
//trans_map.insert({key, value.substr(1)}); //与上条语句等价
else
throw runtime_error("no rule for " + key);
return trans_map;
}
const string &transform(const string &s, const map<string, string> &m)
{
auto map_it = m.find(s);
if (map_it != m.end())
return map_it->second;
else
return s;
}
/*
//transform函数中的find替换为下标运算符
const string &transform(string &s, map<string, string> &m)
{
if (m[s].size())
s = m[s];
return s;
}
*/
void word_transform(ifstream &map_file, ifstream &input_file)
{
auto trans_map = buildMap(map_file);
string text;
while(getline(input_file, 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()
{
ifstream map_file("map.txt"), input_file("input.txt");
word_transform(map_file, input_file);
return 0;
}