map的综合例子

#include<iostream>
#include<string>
#include<map>
#include<fstream>
#include<sstream>
using namespace std;
map<string,string> buildMap(ifstream &map_file);
const string &transform(const string &s,const map<string,string> &m);
void word_transform(ifstream &map_file,ifstream &input)
{
    auto trans_map=buildMap(map_file);//保存转换规则
    string text;                      //保存输入中的一行
    while(getline(input,text))        //读取一行输入
    {
        istringstream stream(text);   //读取每个单词
        string word;
        bool firstword=true;           //控制是否打印空格
        while(stream>>word){
            if(firstword)
                firstword=false;
            else
                cout<<" ";             //在单词间打印一个空格
            cout<<transform(word,trans_map);  //打印输出
        }
        cout<<endl;       //完成一行的转换
    }
}
map<string,string> buildMap(ifstream &map_file)
{
    map<string,string> trans_map;  //保存转换规则
    string key;   //要转换的单词
    string value; //替换后的内容
    while(map_file>>key&&getline(map_file,value))//读取第一个单词存入key中,行中剩余内容存入value
        if(value.size()>1)  //检测是否有转换规则
            trans_map[key]=value.substr(1);  //跳过前导空格
    else 
        throw runtime_error("no rule for "+key);
    return trans_map;
}
const string & transform(const string &s,const map<string,string> &m)
{
    auto map_it=m.find(s); //实际转换规则
    if(map_it!=m.cend()) //如果单词在转换规则map中
        return map_it->second;  //使用替换短语
    else 
        return s;   //否则返回原string
}
int main()
{
    ifstream in1("1.txt");
    ifstream in2("2.txt");
    word_transform(in1,in2);
    return 0;
}
k okay?
y why
r are
u you 
pic picture
thk thanks!
l8r later

以上是1.txt

where r u
y dont u send me a pic
k thk l8r

以上是2.txt

转载于:https://www.cnblogs.com/wuchanming/p/3730066.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值