关联容器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;
}
|
阅读(874) | 评论(0) | 转发(0) |