C++ Primer 第10章 习题10.27

//10.27.cpp
//建立作者及其作品对multimap容器
//使用equal_range函数获取迭代器,然后删除一段范围内的元素
//当所寻找的元素不存在时,程序依然能正确执行
#include<iostream>
#include<map>
#include<string>
using namespace std;

int main()
{
	multimap<string,string> authors;
	string author,work,searchItem;

	//建立作者及其作品的multimap容器
	do
	{
		cout<<"Enter authors name(Ctrl-z to end):"<<endl;
		cin>>author;
		if(!cin)
			break;
		cout<<"Enter author's work(Ctrl-z to end):"<<endl;
		while(cin>>work)
			authors.insert(make_pair(author,work));

		cin.clear();	//读入了一位作者的所有作品后使流对象从新有效
	} while(cin);

	cin.clear();		//使流对象从新有效

	//读入要找的作者
	cout<<"Who is the author you want to erase:"<<endl;
	cin>>searchItem;
	
	//确定该作者对应的multimap元素的范围
	typedef multimap<string,string>::iterator itType;
	pair<itType,itType> pos=authors.equal_range(searchItem);
	
	if(pos.first!=pos.second)
		//删除该作者的所有作品
		authors.erase(pos.first,pos.second);
	else
		cout<<"Can not find this author!"<<endl;

	//输出multimap对象
	cout<<"author\t\twork:"<<endl;
	for(itType iter=authors.begin();
		iter!=authors.end();++iter)
		cout<<iter->first<<"\t\t"<<iter->second<<endl;
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值