问题:定义一个map对象,其元素的键是家族姓氏,而值存储该家族孩子名字的vector对象.为这个map容器输入至少6个条目.通过基于家族姓氏的查询检测你的程序,查询输出该家族所有孩子的名字
解决方案:
#include<iostream>
#include<map>
#include<vector>
#include<string>
using namespace std;
int main()
{
map<string,vetor<string>> children;
string surname,childname;
do{
cou<<"enter surname(Ctrl +Z to end):"<<endl;
cin>>surname;
if(!cin)
break;
vector<string>chd;
pair<map<string,vector<string>>::iterator,bool> ret =
children.insert(make_pair(surname,chd));
if(!ret.second){
cout<<"repeated surname:"<<surname<<endl;
continue;
}
cout<<"enter children's name(Ctrl + Z to end):"<<endl;
while(cin>>childname)
ret.first->second.push_back(chlldname);
cin.clear();
}while(cin)
cin.clear();
cout<<"enter a surname to search:"<<endl;
cin>>surname;
map<string,vector<string>>::iterator iter = children.find(surname);
if(iter = = children.end())
cout<<"no this surname:"<<surname<<endl;
else{
cout<<"chlidren:"<<endl;
vector<string>:: iterator it = iter->second.begin();
while(it != iter->second.end())
cout<<*it++<<endl;
}
return 0;
}
文章评论(0条评论)
登录后参与讨论