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

 



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 }