时间:2021-05-19
使用map实现单词转换的实例分析
从map中查找单词时必须使用find函数,不能使用下表,因为在map中使用下标访问不存在的元素将导致在map容器中添加一个新的元素,新元素的key即要查找的内容。
复制代码 代码如下:
/*****************************************************************************
* 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
}
}
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
本文实例讲述了JS自定义对象实现Java中Map对象功能的方法。分享给大家供大家参考。具体分析如下:Java中有集合,Map等对象存储工具类,这些对象使用简易,
利用commons.BeanUtils实现Obj和Map之间转换,这种是最简单,也是最经常用的publicstaticObjectmapToObject(Map
给定一篇英语文章,要求统计出所有单词的个数,并按一定次序输出。思路是利用go语言的map类型,以每个单词作为关键字存储数量信息,代码实现如下:packagema
本文实例讲述了php最简单的删除目录与文件实现方法。分享给大家供大家参考。具体实现代码如下:复制代码代码如下:原理分析:array_map('rmdir',gl
java中实现list或set转map的方法在开发中我们有时需要将list或set转换为map(比如对象属性中的唯一键作为map的key,对象作为map的val