C++ 单词转换例子

今天在看《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函数。

拓展:我觉得用类似的方法可以实现英语词典,不过当数据量很大时,查找算法效率不是很高。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值