利用map查找对应于key值的mapped value

//下面的这个例子还是比较的经典,这个是课本上的一道习题,答案比较简单,我将以下其进行了整理以实现更丰富的功能:
//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;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值