一个map对象的应用,key(姓氏)—value(名字) 10.18

定义一个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;
}

转载于:https://my.oschina.net/ppppower/blog/36848

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值