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

C++ Primer 第10章 习题10.38

 
阅读更多
//10.28.cpp
//建立作者及其作品的multimap容器
//以下的格式按姓名首字母的顺序输出作者及其作品:
//Author Names Beginning with 'A'
//Author,book,book,.......
//Author Names Beginning with 'B'
//...
#include<iostream>
#include<map>
#include<string>
using namespace std;

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

	//建立作者及其作品的multimap容器
	do{
		cout<<"Enter author name(Ctrl-z to end):"<<endl;
		cin>>author;

		if(!cin)
			break;

		cout<<"Enter author's works(Ctrl-z to end):"<<endl;
		while(cin>>work)
			authors.insert(make_pair(author,work));

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

	//输出multimap对象
	typedef multimap<string,string>::iterator itType;
	itType iter=authors.begin();
	if(iter==authors.end()){
	cout<<"empty multimap!"<<endl;
	return 0;}

string currAuthor,preAuthor;	//记录当前作者及其前一作者
do
{
	currAuthor=iter->first;
	if(preAuthor.empty()||currAuthor[0]!=preAuthor[0])
		//如果出现了首字母不同的作者,则输出该首字母
		cout<<"Author Names Beginning with '"
		<<iter->first[0]<<"':"<<endl;
	//输出作者
	cout<<currAuthor;

	//输出该作者所有作品
	pair<itType,itType> pos=authors.equal_range(iter->first);
	while(pos.first!=pos.second)
	{
		cout<<", "<<pos.first->second;
		++pos.first;
	}
	cout<<endl;			//输出了一个作者的所有作品后,换行

	iter=pos.second;		//iter指向下一作者
	preAuthor=currAuthor;	//将当当前作者设为前一作者
}while(iter!=authors.end());

return 0;
}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics