/* 此代码来自 C++ Primer,手敲一遍是因为: 1. 今天刚好开始学数据结构,好的算法的要满足 健壮性(数据非法时,也能适当作出反应或进行处理) 和 可读性 (便于理解和修改,按照老师的说法,主要体现在注释上),上完课后看C++ Primer,发现下面这段代码,在这两方面就做得比较好,值得学习 2. 因为STL学得还是不太扎实,只是在做题中偶尔用到,但没有系统地学...所以才会重新看书,而只看不敲的话,仍然得不到巩固,记忆也不会深刻 同时,main函数的这种写法,以前虽然看到过,但没有仔细研究,今天仔细查了相关资料了解了一下,发现这个博客讲得很详细 http://www.cnblogs.com/avril/archive/2010/03/22/1691477.html */
//#include <bits/stdc++.h> #include <iostream> #include <map> using namespace std; /* * A program to transform words. * Takes two arguments: The first is name of the word transformation file The second is name of input to transformation * */ int main(int argc, char** argv) { // map to hold the word transformation pairs: // key is the word to look for in the input; value is word to use in the output map<string, string> trans_map; string key, value; if (argc != 3) throw runtime_error ("wrong number of arguments"); // open transformatino file and check that open succeeded ifstream map_file; if (!open_file(map_file, argv[1])) throw runtime_error("no transformation file"); // read the transformation map and build the map while (map_file >> key >> value) trans_map.insert(make_pair(key, value)); // ok, now we're ready to do the transformations // opne the input file and check that the open succeeded ifstream input; if (!open_file(input, argv[2])) throw runtime_error("no input file"); string line; // hold each line from the input // read the text to transform it a line at a time while (getline(input, line)) { istringstream stream(line); // read the line a word a time string word; bool firstword = true; // controls wheter a space is printed while (stream >> word) { // ok: the actual mapwork, this part is the heart of the program map<string, string>::const_iterator map_it = trans_map.find(word); // if this word is in the transformation map if (map_it != tran_map.end()) // replace it by the transformation value int the map word = map_it->second; if (firstword) firstword = false; else cout << " "; // print space between words cout << word; } cout << endl; } return 0; }