//下面的这个例子还是比较的经典,这个是课本上的一道习题,答案比较简单,我将以下其进行了整理以实现更丰富的功能:
//Exercise
//10.18:
//定义一个 map 对象,其元素的键是家庭姓氏,而值则是存储该家庭孩子名字的 vector 对象。为这个 map 容器输入至少六个条目。通过基于家庭姓氏的查询检测你的程序,//查询应输出该家庭所有孩子的名字。
#include <vector>
#include <fstream>
#include <sstream>
#include <stdexcept>
using namespace std;
ifstream &open_file(ifstream &in,const string &filename)
{
in.close();
in.clear();
in.open(filename.c_str());
return in;
}
int main(int argc,char**argv)
{
map<string,vector<string> > name_search;
vector<string> sear_child;
string name;
string surname;
string lines;
ifstream f_map;
if(!open_file(f_map,argv[1]))
throw runtime_error("cant't open the file for transformation!");
while(getline(f_map,lines))
{
istringstream stream(lines);
stream>>surname;
sear_child.clear();
while(stream>>name)
sear_child.push_back(name);
pair<map<string,vector<string> >::iterator , bool> ret=name_search.insert(make_pair(surname,sear_child));
cout<<"/***********测试*****************/"<<endl;
cout<<"*********************************"<<endl;
vector<string>::iterator beg=sear_child.begin();
while(beg!=sear_child.end())
cout<<*beg++<<" ";
cout<<endl;
cout<<"*********************************"<<endl;
cout<<"*********************************"<<endl;
if(!ret.second) cout<<"*********************************"<<endl;
if(!ret.second)
{
cout<<"insert fails!"<<endl;
continue;
}
}
ifstream input;
if(!open_file(input,argv[2]))
throw runtime_error("cant't open the input file!");
string name_word;
string nameword_search;
while(getline(input,name_word))
{
istringstream stream(name_word);
while(stream>>nameword_search)
{
map<string,vector<string> >::iterator result=name_search.find(nameword_search);
if(result!=name_search.end())
{
vector<string>::iterator beg=(result->second).begin();
while(beg!=(result->second).end())
cout<<*beg++<<" ";
}
else
cout<<nameword_search<<" ";
}
cout<<endl;
}
return 0;
}
利用map查找对应于key值的mapped value
最新推荐文章于 2021-08-12 20:50:19 发布