前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >map对象建立家族姓氏查询

map对象建立家族姓氏查询

作者头像
猿人谷
发布2018-01-17 12:11:28
5960
发布2018-01-17 12:11:28
举报
文章被收录于专栏:猿人谷猿人谷

题目:定义一个map对象,其元素的键是家族姓氏,而值是存储该家族孩子名字的vector对象。为这个map容器输入至少六个条目。通过基于家族姓氏的查询检测你的程序,查询应输出该家族所有孩子的名字。

代码语言:javascript
复制
 1 //定义一个map对象,其元素的键是家族姓氏
 2 //而值则是存储该家族孩子名字的vector对象
 3 //进行基于家族姓氏的查询,输出该家族所有孩子的名字
 4 #include<iostream>
 5 #include<map>
 6 #include<vector>
 7 #include<string>
 8 using namespace std;
 9 
10 int main()
11 {
12     map<string , vector<string> > children;
13     string surname , childName;
14 
15     //读入条目(家族姓氏及其所有孩子的名字)
16     do{
17         cout<<"Enter surname: "<<endl;
18         cin>>surname;
19         if(!cin)  //读入结束
20             break;
21         //插入新条目
22         vector<string> chd;
23         pair<map<string , vector<string> >::iterator , bool> ret = children.insert(make_pair(surname , chd));
24 
25         if(!ret.second){//该家族姓氏已在map容器中存在
26             cout<<"repeated surname: "<<surname<<endl;
27             continue;
28         }
29 
30         cout<<"Enter children's name: "<<endl;
31         while(cin>>childName)//读入该家族所有孩子的名字
32             ret.first->second.push_back(childName);
33         cin.clear(); //使输入流重新有效    
34     }while(cin);
35 
36     cin.clear(); //使输入流重新有效
37 
38     //读入要查询的家族
39     cout<<"Enter a surname to search: "<<endl;
40     cin>>surname;
41 
42     //根据读入的家族姓氏进行查找
43     map<string , vector<string> >::iterator iter = children.find(surname);
44 
45     //输出查询结果
46     if(iter == children.end()) //找不到该家族姓氏
47         cout<<"no this surname: "<<surname<<endl;
48     else
49     {
50         cout<<"children: "<<endl;
51         //输出该家族中所有孩子的名字
52         vector<string>::iterator it = iter->second.begin();
53         while(it != iter->second.end())
54             cout<<*it++<<endl;
55     }
56 
57     return 0;
58 }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2013-09-04 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档