C++Primer第五版 练习11.38-2单词转换程序(解答)
2015-10-14 16:25
495 查看
练习11.38:用unordered_map重写单词计数程序(参加11.1节,第375页)和单词转换程序(参见11.3.6节,第391页)。
map_file.txt
data_input.txt
[code]/* *C++Primer第五版 *练习11.38 *2015/10/14 *问题描述:练习11.38:用unordered_map重写单词计数程序(参加11.1节,第375页)和单词转换程序(参见11.3.6节,第391页)。 *说明:在练习11.33基础上替换 *作者:Nick Feng *邮箱:nickgreen23@163。com */ /* *C++Primer第五版 *练习11.33 *2015/10/14 *问题描述:练习11.33:实现你自己版本的单词转换程序。 *说明:把书上的程序自己再敲了一遍 *作者:Nick Feng *邮箱:nickgreen23@163。com */ #include <iostream> #include <vector> #include <map> #include <fstream> #include <string> #include<sstream> #include <tr1/unordered_map> using namespace std; //建立转换映射 std::tr1::unordered_map<string, string> buildMap(ifstream &map_file) { std::tr1::unordered_map<string, string> trans_map; //保存转换规则 string key; //要转换的单词 string value; //替换后的内容 //读取第一个单词存入key中,行中剩余内容存入value while (map_file >> key && getline(map_file, value)) if(value.size() > 1) //检查是否有转换规则 trans_map[key] = value.substr(1); //跳过前导空格 else throw runtime_error("no rule for " + key); return trans_map; } //生成转换文本 const string & transform(const string &s, const std::tr1::unordered_map<string,string> &m) { //实际的转换工作;此部分是程序的核心 auto map_it = m.find(s); //如果单词在转换规则map中 if (map_it != m.end()) //cend改为end return map_it -> second; //使用替换语句 else return s; //否则返回原string } /*单词转换程序*/ void word_transform(ifstream &map_file, ifstream &input) { auto trans_map = buildMap(map_file); //保存转换规则 string text; while (getline(input, text)) { istringstream stream(text); //读取每个单词 string word; bool firstword = true; //控制是否打印空格 while (stream >> word){ if (firstword) firstword = false; else cout << " "; //在单词间打印一个空格 //transform 返回它的第一个参数或其他转换之后的形式 cout << transform(word, trans_map); //打印输出 } cout << endl; //完成一行的转换 } } int main() { ifstream file1("map_file.txt"); //转换的规则 ifstream file2("data_input.txt"); //输入的文件 word_transform(file1, file2); return 0; }
map_file.txt
[code]brb be right back k okay? y why r are u you pic picture thk thanks! 18r later
data_input.txt
[code]where r u y dont u send me a pic k thk 18r
相关文章推荐
- C++Primer第五版 练习11.38-1单词统计程序(解答)
- C++STL学习(3)容器list
- C++Primer第五版 11.4节练习
- c++虚函数、内存布局
- C++ 多态
- C语言获取文件SHA1哈希
- c++智能指针
- C语言--getchar()的使用
- string对象中去掉标点符号
- C++Primer第五版 练习11.33
- C++Primer第五版 11.3.6节练习
- C语言--函数的调用
- [c++] LeetCode Add Two Numbers问题
- C语言的查找方法--折半查找
- 排序算法----冒泡排序+插入排序+选择排序+快速排序+希尔排序+堆排序+归并排序+计数排序+基数排序+桶排序(c语言)
- C++虚函数及虚函数表解析
- C++Primer学习:智能指针与动态内存(2)
- C语言的递归算法--猴子摘桃问题
- C++中include<> 与 include" " 的区别
- c++11 bind注意