本文共 763 字,大约阅读时间需要 2 分钟。
今天在看《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函数。拓展:我觉得用类似的方法可以实现英语词典,不过当数据量很大时,查找算法效率不是很高。
转载地址:http://wwklf.baihongyu.com/