您的位置:首页 > 编程语言 > C语言/C++

C++primer学习:关联容器练习(4)

2015-10-10 23:14 302 查看

单词转换程序:将一个文本中的单词按照另一个文本的转换规则,替换成另外一个文本中的单词.并且开头字母大写;

#include  "iostream"
#include "vector"
#include "list"
#include "map"
#include "set"
#include "string"
#include "algorithm"
#include "utility"
#include "fstream"
#include "sstream"
using namespace std;
map<string,string> build_map(ifstream&map_file)
{
map<string, string> Trans;
string line, word;
while (map_file>>word&&getline(map_file,line))
{
Trans[word] = line.substr(1);//去掉空格
}
return Trans;
}
string convert(const map<string,string>&Trans_map,const string &word)
{
auto pos = Trans_map.find(word);
return (pos == Trans_map.cend() ? word : pos->second);
}
void word_transform(string filename1,string filename2)
{
ifstream map_file(filename1), input_file(filename2);
auto trans_map = build_map(map_file);
string word, line;
while (getline(input_file,line))//获取输入内容
{
istringstream is(line);
string line2;
while (is >> word)//读入输入的单词
line2 += convert(trans_map, word)+" ";
if (!(ispunct(line2[0]) || isdigit(line2[0])))
line2[0] = toupper(line2[0]);

cout <<line2<< endl;
}
}
int main()
{
word_transform("Text1.txt", "Text2.txt");
return 0;
}




输入:

where r you

y dont u send me a pic

k thk 18r

“I am the king of wor

转换规则:

k okay

y why

r are

u you

pic picture

thk thanks!

18r later

===================================================================

无序关联容器,不需要维护容器的序.使用==来比较函数,hash函数来生成每个对象的key值.它在存储上组织为一组桶,桶里面管理着0个或者多个元素.并且提供了一系列桶的接口与管理操作.

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: