定义一个map对象,其元素的键是家族姓氏,元素的值是家族中孩子的名字。
查找指定的姓氏检验你的程序。
#include<iostream>
#include<map>
#include<vector>
#include<string>
using namespace std;
int main()
{
map<string,vector<string> > nameMap;
cout<<"***Enter lastname:(Ctrl+d to end)"<<endl;
string lastName;
while(cin>>lastName)
{
string s;
getline(cin,s); //读走回车换行符
vector<string> firstNameVec;
//把键-值对插入map对象中
pair<map<string,vector<string> >::iterator,bool> ret=nameMap.insert(make_pair(lastName,firstNameVec));
if(!ret.second)
{
cout<<"***repeated lastname!"<<'\t'
<<"Enter lastname:(Ctrl+d to end)"<<endl;
continue;
}
//input some firstnames
cout<<"***Enter some firstnames:(Ctrl+d to end)"<<endl;
string firstName;
while(cin>>firstName)
ret.first->second.push_back(firstName);
cin.clear(); //恢复流状态
cout<<"***Enter lastname:(Ctrl+d to end)"<<endl;
}
cin.clear();
//output
cout<<endl<<"***name:"<<endl;
for(map<string,vector<string> >::iterator iter=nameMap.begin();iter!=nameMap.end();++iter)
{
cout<<iter->first<<": ";
for(vector<string>::iterator it=(iter->second).begin();it!=(iter->second).end();++it)
cout<<*it<<' ';
cout<<endl;
}
//通过基于姓氏的键查询,并输出所有名字
cout<<"***Enter a lastname you are looking:"<<endl;
cin>>lastName;
map<string,vector<string> >::iterator it=nameMap.find(lastName);
if(it==nameMap.end())
cout<<"***we do not have this lastname!"<<endl;
else
{
cout<<"***The firstname are: ";
for(vector<string>::iterator it2=it->second.begin();it2!=it->second.end();++it2)
cout<<*it2<<' ';
cout<<endl;
}
return 0;
}