C++ Primer(第5版) 练习 17.33
练习 17.33 修改11.3.6节(第392页)中的单词转换程序,允许对一个给定单词有多种转换方式,每次随机选择一种进行实际转换。
环境:Linux Ubuntu(云服务器)
工具:vim
代码块
map<string, vector<string>> buildMap(ifstream &map_file){map<string, vector<string>> trans_map;string key, value;while(map_file>>key && getline(map_file, value)){if(value.size() > 1){trans_map[key];trans_map[key].push_back(value.substr(1));}else{throw runtime_error("no rule for " + key); }}return trans_map;
}const string &transform(const string &s, const map<string, vector<std::string>> &m){map<string, vector<std::string>>::const_iterator map_it = m.find(s);static default_random_engine e;if(map_it != m.cend()){if(map_it->second.size() == 1){return map_it->second[0];}else{uniform_int_distribution<unsigned> u(0, map_it->second.size()-1);return map_it->second[u(e)];}}else{return s;}
}void word_transform(ifstream &map_file, ifstream &input){map<string, vector<string>> trans_map = buildMap(map_file);string text;while(std::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;}
}