`
bcyy
  • 浏览: 1831328 次
文章分类
社区版块
存档分类
最新评论

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;
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics