Chinaunix首页 | 论坛 | 博客
  • 博客访问: 327805
  • 博文数量: 69
  • 博客积分: 2090
  • 博客等级: 大尉
  • 技术积分: 708
  • 用 户 组: 普通用户
  • 注册时间: 2008-09-23 09:31
文章分类

全部博文(69)

文章存档

2012年(1)

2011年(4)

2010年(48)

2009年(14)

2008年(2)

我的朋友

分类: C/C++

2010-04-23 21:07:51

 关联容器map是一组键-值的集合。
 以下是用map实现单词转换的代码
 具体的要求是给出一个字符串。然后把它转换为另一个字符串。
 在in1文件中存放对应关系
 i  I
 cm come
 fm from
 cha china
 a   and
 lv  love
 在另一个文件中存放字符一组字符串
 i cm fm cha
 a i lv cha
 根据这两个源文件得到
 I come from china
 and i love china
 并且将得到的目的文件输出到out文件中
 
 
 
 

#include <iostream>
#include <string>
#include <fstream>
#include <map>
#include <utility>
#include <sstream>


using namespace std;

int main(int argc,char **argv)
{
     ifstream in1("in1");
    ifstream in2("in2");
    ofstream out("out");


    string key,value;
    string inString;
    string outString;
    
    map<string,string> trans_map;
    if(!in1.good())
    {
        cerr << "open in1 error!\n";
        return -1;
    }

    if(!in2.good())
    {
        cerr << "open in2 error\n";
        return -1;
    }

    while(in1 >> key >> value)
    {
        trans_map.insert(make_pair(key,value));
    }

    map<string,string>::iterator map_it;

    string line;

    
    while(getline(in2,line))
    {
            istringstream stream(line);
            while(stream >> inString)
            {
                map_it = trans_map.find(inString);
                if(map_it != trans_map.end())
                out << map_it->second<<" ";        
                
            }
        out << endl;
    }
    
    in1.close();
    in2.close();
    out.close();

    return 0;
}


阅读(843) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~