C++ Primer 第10章 习题10.27

来源:互联网 发布:php require 语言结构 编辑:程序博客网 时间:2024/06/05 15:57
//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);elsecout<<"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;}