Example analysis of using map to realize word conversion
When you look up a word from a map, you must use the Find function and you cannot use the following table, because using subscript to access a nonexistent element in a map causes a new element to be added to the map container, and the key of the new element is the content to find.
Copy Code code as follows:
/*****************************************************************************
* Open File
*****************************************************************************/
ifstream& Open_file (ifstream &in, const string &file)
{
In.close (); Close in case it is already open
In.clear (); Clear any existing errors
If the "open fails", the stream would be in a invalid state
In.open (File.c_str ()); Open the file we were given
return in; Condition 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
while (getline (input, line))
{
Istringstream stream (line); Read the line a word in a time
string Word;
bool BFIRSTWORDFLG = true; Controls whether a is printed
while (stream >> word)
{
ok:the actual mapwork, this is the heart of the program
map<string, String>::const_iterator map_it = Trans_map.find (word);
If This word was 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
}
}