您的位置:首页 > 其它

map 容器小例(hash map)

2015-12-09 20:32 288 查看
<span style="font-size:18px;">//导入两个文件t1存放映射规则,t2存放内容,将t2中的内容通过t1映射出来
/* t1
brb be right back
k okay?
y why
r are
u you
pic picture
thk thanks!
18r later
*/
/* t2
where r u
y dont u send me a pic
k thk 18r
*/

#include<iostream>
#include<fstream>
#include<sstream>
#include<map>
#include<unordered_map>
//using namespace std;
std::unordered_map<std::string,std::string> buildMap(std::ifstream &map_file);
const std::string &
transform(const std::string &s,const std::unordered_map<std::string,std::string>&m);
void word_transform(std::ifstream &map_file,std::ifstream &input)
{
auto trans_map=buildMap(map_file);
std::string text;
while(getline(input,text)){
std::istringstream stream(text);
std::string word;
bool firstword=true;
while(stream>>word){
if(firstword)
firstword=false;
else
std::cout<<" ";
std::cout<<transform(word,trans_map);
}
std::cout<<std::endl;
}
}
std::unordered_map<std::string,std::string> buildMap(std::ifstream &map_file)
{
std::unordered_map<std::string,std::string>trans_map;
std::string key;
std::string value;
while(map_file>>key&&getline(map_file,value))
if(value.size()>1)
trans_map[key]=value.substr(1);
else
throw std::runtime_error("no rule for"+key);
return trans_map;
}
const std::string &
transform(const std::string &s,const std::unordered_map<std::string,std::string>&m)
{
auto map_it=m.find(s);
if(map_it!=m.cend())
return map_it->second;
else
return s;
}
int main()
{
std::ifstream map_file,input;
map_file.open("C:\\Users\\ACM\\Desktop\\t1.txt");
input.open("C:\\Users\\ACM\\Desktop\\t2.txt");
word_transform(map_file,input);
return 0;</span>
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: