使用map實現單詞轉換的程式
從map中尋找單詞時必須使用find函數,不能使用下表,因為在map中使用下標訪問不存在的元素將導致在map容器中添加一個新的元素,新元素的key即要尋找的內容。
/*****************************************************************************<br />* Open file<br />*****************************************************************************/<br />ifstream& open_file(ifstream &in, const string &file)<br />{<br />in.close(); // close in case it was already open<br />in.clear(); // clear any existing errors</p><p>// if the open fails, the stream will be in an invalid state<br />in.open(file.c_str()); // open the file we were given</p><p>return in; // condition state is good if open succeeded<br />}</p><p>/*****************************************************************************<br />* Word Transform<br />*****************************************************************************/<br />void WordTransform(const string rule, const string infile)<br />{<br />if (rule.empty() || infile.empty())<br />{<br />return;<br />}</p><p>map<string ,string> trans_map;<br />string key, value;</p><p>// Open transformation file and check that open succeeded<br />ifstream map_file;<br />if (!open_file(map_file, rule))<br />{<br />throw runtime_error("No transformation file.");<br />}</p><p>// Read the transformation map and build the map<br />while (map_file >> key >> value)<br />{<br />trans_map.insert(make_pair(key, value));<br />}</p><p>// Open the input file and check that the open succeeded<br />ifstream input;<br />if (!open_file(input, infile))<br />{<br />throw runtime_error("No input file.");<br />}</p><p>string line; // Hold each line from the input</p><p>// Read the text to transform it a line at a time<br />while (getline(input, line))<br />{<br />istringstream stream(line);// Read the line a word at a time<br />string word;<br />bool bFirstWordFlg = true;// Controls whether a space is printed<br />while (stream >> word)<br />{<br />// ok: the actual mapwork, this part is the heart of the program<br />map<string, string>::const_iterator map_it = trans_map.find(word);</p><p>// If this word is in the transformation map<br />if (map_it != trans_map.end())<br />{<br />// Replace it by the transformaion value in the map<br />word = map_it->second;<br />}</p><p>if (bFirstWordFlg)<br />{<br />bFirstWordFlg = false;<br />}<br />else<br />{<br />cout << " ";// Print space between words<br />}</p><p>cout << word;<br />}<br />cout << endl;// Done with this line of input<br />}<br />}<br />