Example Analysis of word conversion using map
You must use the find function when searching words in a map. The following table cannot be used, because accessing nonexistent Elements Using subscript in a map will add a new element to the map container, the key of the new element is the content to be searched.
Copy codeThe Code is as follows: /*************************************** **************************************
* Open file
**************************************** *************************************/
Ifstream & open_file (ifstream & in, const string & file)
{
In. close (); // close in case it was already open
In. clear (); // clear any existing errors
// If the open fails, the stream will be in an invalid state
In. open (file. c_str (); // open the file we were given
Return in; // condition state is good if open succeeded
}
/*************************************** **************************************
* Word Transform
**************************************** *************************************/
Void WordTransform (const string rule, const string infile)
{
If (rule. empty () | infile. empty ())
{
Return;
}
Map <string, string> trans_map;
String key, value;
// Open transformation file and check that open succeeded
Ifstream map_file;
If (! Open_file (map_file, rule ))
{
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 ));
}
// Open the input file and check that the open succeeded
Ifstream input;
If (! Open_file (input, infile ))
{
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 at a time
String word;
Bool bFirstWordFlg = true; // Controls whether 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! = Trans_map.end ())
{
// Replace it by the transformaion value in the map
Word = map_it-> second;
}
If (bFirstWordFlg)
{
BFirstWordFlg = false;
}
Else
{
Cout <"; // Print space between words
}
Cout <word;
}
Cout <endl; // Done with this line of input
}
}