今天在看《C++primer》的时候书上有一道例子,于是就自己实现了一遍。
例子的名称叫做单词转换,使用了map对象,难度并不大。
实现思路:
先把单词都存到一个文件里面,文件名叫dictionary.txt。
然后代码如下:
#include<iostream>
#include<string>
#include<map>
#include<sstream>
#include<fstream>
using namespace std;
void init(map<string, string> &word_change)
{
string str;
string front,last;
ifstream ifs("dictionary.txt");
while(ifs>>front>>last)
word_change.insert(make_pair(front,last));
}
void main()
{
string str,temp,changed="";
map<string,string> word_change;
init(word_change);
getline(cin,str);
stringstream ss(str);
while(!ss.eof())
{
ss.clear();
ss >>temp;
if(word_change.count(temp))
temp = word_change[temp];
changed+=temp+" ";
}
cout<<changed<<endl;
system("pause");
}
我在查找单词的时候用的是count函数,也可以用find函数。
拓展:我觉得用类似的方法可以实现英语词典,不过当数据量很大时,查找算法效率不是很高。
本文详细介绍了如何使用C++实现单词转换功能,并通过文件读取和map对象进行操作。此外,还讨论了类方法在构建英语词典时的效率问题及改进策略。
3663

被折叠的 条评论
为什么被折叠?



