CPrimer第10章-關(guān)聯(lián)容器-課后習題答案_第1頁
CPrimer第10章-關(guān)聯(lián)容器-課后習題答案_第2頁
CPrimer第10章-關(guān)聯(lián)容器-課后習題答案_第3頁
CPrimer第10章-關(guān)聯(lián)容器-課后習題答案_第4頁
CPrimer第10章-關(guān)聯(lián)容器-課后習題答案_第5頁
已閱讀5頁,還剩22頁未讀 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)

文檔簡介

第10章關(guān)聯(lián)容器

L編寫程序讀入一些列string和int型數(shù)據(jù),將每一組存儲在一個pair對象中,然后將這些

pair對象存儲在vector容器里。

//ll.16_10.l_pair.cpp:定義控制臺應(yīng)用程序的入口點。

//

include"stdafx.h"

#include<iostream>

include<string>

#include<vector>

#include<utility>

usingnamespacestd;

int_tmain(intargc,_TCHAR*argv[])

(

stringstr;

intiVal;

A

cout?"\tlnputsomepaircontents)pair<stringzint>)(Ztoend):\n";

vector<pair<string,int>>pairVec;

while(cin?str?iVal)

pairVec.push_back(pair<string,int>(str,iVal));

cout?"\n\tThecontentofpairVecis:\n";

for(vector<pair<string,int>>::iteratorit=pairVec.begin();it!=pairVec.end();++it)

{

cout?it->first?""?it->second?endl;

)

system("pause");

return0;

c、e:\hh<\hh<progra>\11.16_10.l_pair\debug\l1.16_10.l_pair.exe

Inputsomepaircontents<pair<stringJ.int>><人Ztoend>:

biello1

LorId2

Wauy3

rZ

ThecontentofpairUecis:

biello1

LorId2

klauy3

情按任意鍵繼續(xù)?.?

2.在前一題中,至少可使用三種方法創(chuàng)建pair對象。編寫三個版本的程序,分別采用不同的

方法來創(chuàng)建pair對象。你認為哪一種方法更易于編寫和理解,為什么?

stringstr;

intiVal;

vector<pair<string,int>>pairVec;

pair<string,int>newPair;

while(cin?str?iVal)

(

//firstmethod

pairVec.push_back(pair<string,int>(str,iVal));

//thesecondmethod

newPair=make__pair(str,iVal);

pairVec.push_back(newPair);

)

//thirdmethod

while(cin?newPair.first?newPair.second)

(

pairVec.push_back(newPair);

}

第二種方法更好一些,更容易閱讀和理解。因為它調(diào)用了make_pair函數(shù),可以明確地表明

確實生成了pair對象這一行為。

3.描述關(guān)聯(lián)容器和順序容器的差別。

兩者的本質(zhì)差別在于:關(guān)聯(lián)容器通過鍵key存儲和讀取元素,而順序容器則通過元素在容

器中的位置順序存儲和訪問元素。

4.舉例說明list、vector,deque、map以及set類型分別使用的情況。

list類型適用于需要在容器的中間位置插入和刪除元素的情況,如以無序的方式讀入一系列

學(xué)生的數(shù)據(jù);

vector類型適用于需要隨機訪問元素的情況。如:在學(xué)號為l...n的學(xué)生中,訪問第x學(xué)號

的學(xué)生的信息。

deque類型適用于在容器的尾部或首部有插入和刪除元素情況。如:對服務(wù)窗口先來先服務(wù)

的情況。

map適用于需要key-value對的集合的情況。如:字典電和話簿的建立和使用。

set類型適用于使用鍵集合的情況。例如,黑名單的建立和使用。

5.定義一個Map對象,將單詞與一個list對象關(guān)聯(lián)起來,該list對象存儲對應(yīng)的單詞可能出

現(xiàn)的行號。

map<string,list<int>>wordLines;

6.可否定義一個map對象以vector<int>::interator為鍵關(guān)聯(lián)int型對象?如果以

list<int>::iterator關(guān)聯(lián)int型對象呢?或者,以pairvint,string〉關(guān)聯(lián)int?對于每種情況,如果

允許,請解釋其原因。

可以定義一個map對象以vector<int>::iterator和pair<int,string>為鍵關(guān)聯(lián)int型對象。

不能定義第二種情況,因為鍵類型必須支持<操作,而list容器的迭代器類型不支持(操作。

pair<int,string〉關(guān)聯(lián)int可以。

7.對于以int型對象為索引關(guān)聯(lián)vector<int>型對象的map容器,它的mapped_type。key_type

和value_type分別是什么?

分另是:vector<int>,int和pair<constint,vector<int>>。

8.編寫一個表達式,使用map的迭代器給其元素賦值。

map<string,int>m;

map<string,int>::iteratormapjt=m.begin();

map_it->second=val;//只能對map的值成員元素賦值。不能對鍵進行賦值。

9.編寫程序統(tǒng)計并輸出所讀入的單詞出現(xiàn)的次數(shù)。

//ll.16_10.9_wordcount.cpp:定義控制臺應(yīng)用程序的入口點。

//

include"stdafx.h"

#include<iostream>

include<string>

#include<utility>

include<map>

usingnamespacestd;

int__tmain(intargc,_TCHAR*argv[])

(

map<string,int>wordCount;

stringword;

while(cin?word)

(

++wordCount[word];

cout?"Theword?word?appearsfor"

?wordCount[word]?"times."?endl;

}

system("pause");

return0;

c'e:\hh<\hhwprogra>\l1.16_10.9_wordcoi

■liello

|Thev/ordiello.appearsfor1times.

world

Theword'world/appearsfor1tines.

hello

Thewordniello,appearsfor2tines.

dauy

Theviord,dauy,appearsfor1tines.

i

Thev/ord*I*appearsfor1tines.

don't

Thev/ord*don*t*appearsfor1tines.

luanna

Theviord9v/anna*appearsfor1tines.

eat

Theviord‘eat'appearsfor1tines.

the

Theviord9theJappearsfor1tines.

■lunch

1Thev/ord'lunch"appearsfor1tines.

ok

Theword'ok'appearsfor1tines.

ok

Theword'ok'appearsfor2tines.

人Z

請按任意鍵繼續(xù)...

10.解釋下面程序的功能:

map<int,int>m;

m[0]=1;

比較上一程序和下面程序的行為

vector<int>v;

v[0]=1;

首先創(chuàng)建一個空的map容器m,然后再m中增加一個鍵為。的元素,并將其值賦值為1,

第二段程序?qū)⒊霈F(xiàn)運行時錯誤,因為v為空的vector對象,其中下標為0的元素不存在。對

于vector容器,不能對尚不存在的元素直接賦值,只能使用push_back,insert等函數(shù)增加

元素。

11.哪些類型可用做map容器對象的下標?下標操作符返回的又是什么類型?給出一個具體

例子說明,即定義一個map對象,指出哪些類型可用作其下標,以及下標操作符返回的類

型。

可用作map容器的對象的下標必須是支持<操作符的類型。

下標操作符的返回類型為map容器中定義的mapped_type類型。

如map<string,int>wordCount;

可用于其下標的類型為string類型以及C風格字符串類型,下標的操作符返回int類型。

12.重寫10.3.4節(jié)習題的單詞統(tǒng)計程序,要求使用insert函數(shù)代替下標運算。你認為哪個程

序更容易編寫和閱讀?請解釋原因。

1111.16_10.12_wordCount_insert.cpp:定義控制臺應(yīng)用程序的入口點。

//

#include"stdafx.h"

include<iostream>

include<string>

#include<utility>

#include<map>

usingnamespacestd;

int_tmain(intargc,_TCHAR*argv[])

(

cout?"Inputsomewords(Ctrl+ztoend):"?endl;

map<string,int>wordCount;

stringword;

while(cin?word)

(

pair<map<string,int>::iterator,bool>ret=

wordCount.insert(make_pair(word,1));

if(!ret.second)

++ret.first->second;

)

for(map<string,int>::iteratorit=wordCount.begin();it!=wordCount.end();++it)

(

cout?”Thewordappearsfor"?(*it).second?"times."?

endl;

)

system("pause");

return0;

)

~C:\¥INDOTS\systeM32\c>d.exe

Inputsoneviords<Ctrl+ztoend〉:

amsothirsty,Iwanttohaueadrinknun

k,youjusttohaueadrink.

Lt

Theword','appearsfor3times.

Theviordappearsfor1tines.

Theword,19appearsfor2tines.

Theword'a'appearsfor2times.

Theword'am'appearsfor1tines.

Theviord9drink*appearsfor2tines.

Thev/ord'haue'appearsfor2times.

Theword'just'appearsfor1times.

Theword'mum'appearsfor1times.

Theviord'ok'appearsfor1tines.

Theviord9so9appearsfor1times.

Theviord9thirsty*appearsfor1times.

Theword*to9appearsfor2times.

Theviord9wantJappearsFor1times.

Theword'you'appearsfor1times.

情按任意鍵繼續(xù)..

13.假設(shè)有mapvstring,vector<int>>類型,指出在該容器中插入一個元素的insert函數(shù)應(yīng)具

有的參數(shù)類型和返回值類型。

參數(shù)類型:pair<conststring,vector<int>>

返回值類型:pair<map<string,vector<int>>::iterator,bool>

14.map容器的count和find運算有何區(qū)別?

前者返回map容器中給定的鍵K的出現(xiàn)次數(shù),且返回值只能是0或者1,因為m叩只允許一個

鍵對應(yīng)一個實例。

后者返回給定鍵K元素索引時指向元素的迭代器,若不存在此K值,則返回超出末端迭代器。

15.你認為count適合用于解決哪一類問題?而find呢?

count適合用于判斷map容器中某鍵是否存在,find適合用于在map容器中查找指定鍵對應(yīng)

元素。

16.定義并初始化一個變量,原來存儲調(diào)用鍵為string,值為vector<int>的map對象的find

函數(shù)的返回結(jié)果。

map<string,vector<int>>::iteratorit=xMap.find(K);

”,上述轉(zhuǎn)換程序使用了find函數(shù)來查找單詞:

map<string,string>::const_iteratormapjt=trans_map.find(word);

你認為這個程序為什么要使用find函數(shù)?如果使用下標操作符又會怎樣?

使用find函數(shù),是為了當文本中出現(xiàn)的單詞word是要轉(zhuǎn)換的單詞時,獲取該元素的迭代器,

以便獲取對應(yīng)的轉(zhuǎn)換后的單詞。

如果使用下標,則必須先通過使用count函數(shù)來判斷元素是否存在,否則,當元素不存在時,

會創(chuàng)建新的元素并插入到容器中從而導(dǎo)致單詞轉(zhuǎn)換結(jié)果不是預(yù)期效果

18.定義一個map對象,其元素的鍵是家族姓氏,而值則是存儲該家族孩子名字的vector對

象。為這個map容器輸入至少六個條目。通過基于家族姓氏的查詢檢測你的程序,查詢應(yīng)

輸出該家族所有孩子的名字。

//11..16_10.18_map_vector_children'sName.cpp:定義控制臺應(yīng)用程序的入口點。

//

include"stdafx.h"

#include<iostream>

include<string>

#include<vector>

include<utility>

#include<map>

usingnamespacestd;

int__tmain(intargc,_TCHAR*argv[])

map<string,vector<string>>children;

stringfamName,childName;

do

(

cout?"Inputfamilies'name(Ctrl+ztoend):"?endl;

cin?famName;

if(!cin)

break;

vector<string>chd;

pair<map<string,vector<string>>::iterator,bool>ret=

children.insert(make_pair(famName,chd));

if(!ret.second)

(

cout?"Alreadyexistthefamilyname:"?famName?endl;

continue;

)

cout?"\n\tlnputchildren'sname(Ctrl+ztoend):"?endl;

while(cin?childName)

ret.first->second.push_back(childName);

cin.clear();

}while(cin);

cin.clear();

cout?"\n\tlnputafamilynametosearch:"?endl;

cin?famName;

map<string,vector<string>>::iteratoriter=children.find(famName);

if(iter==children.end())

cout?"\n\tSorry,thereisnotthisfamilyname:"?famName?endl;

else

(

cout?"\n\tchildren:"?endl;

vector<string>::iteratorit=iter->second.begin();

while(it!=iter->second.end())

cout?*it++?endl;

}

system("pause");

return0;

C:\¥I!iDO¥S\syste>32\od.eze

IInputfamilies'nane<Ctrl?ztoend>:

Inputchildren*jsname<Ctrl+2:toend>:

Hqianhui

1Inputfamilies'narne<Ctrl+ztoend>:

Jwang

1Alreadyexistthefamilyname:wang

Inputfamilies'nane<Ctrl+ztoend>:

liwang

InputchildrenJisname<Ctrl+2:toend>:

^jeijiaokun

卜z

InputFamilies'nane<Ctrl+:ztoend>:

1rz

Inputafamilylanetosearch:

1uang

children:

1qian

1!hui

1情按任意鍵繼續(xù)...

19.把上一題的map對象再擴展一下,使其vector對象存儲pair類型的對象,記錄每個孩子

的名字和生日。相應(yīng)地修改程序,測試修改后的測試程序以檢查所編寫的m叩是否正確。

include"stdafx.h"

#include<iostream>

include<string>

#include<vector>

include<utility>

#include<map>

usingnamespacestd;

int__tmain(intargc,_TCHAR*argv[])

(

map<string,vector<pair<string,string>>>children;

stringfamName,childName,childBday;

do

(

cout?"\nInputfamilies'name(Ctrl+ztoend):"?endl;

cin?famName;

if(!cin)

break;

vector<pair<string,string>>chd;

pair<map<string,vector<pair<string,string>>>::iterator,bool>ret=

children.insert(make_pair(famName,chd));

if(!ret.second)

(

cout?"\nAlreadyexistthefamilyname:"?famName?endl;

continue;

)

cout?"\tlnputchildren'snameandbirthday(Ctrl+ztoend):"?endl;

while(cin?childName?childBday)

ret.first->second.push_back(make_pair(childName,childBday));

cin.clear();

}while(cin);

cin.clear();

cout?"\n\tlnputafamilynametosearch:"?endl;

cin?famName;

map<string,vector<pair<string,string>>>::iteratoriter=children.find(famName);

if(iter==children.end())

cout?"\n\tSorry,thereisnotthisfamilyname:"?famName?endl;

else

(

cout?"\n\tThefamily'schildrenandeverychild'sbirthdayis:"?endl;

vector<pair<string,string>>::iteratorit=iter->second.begin();

while(it!=iter->second.end())

(

cout?(*it).first?"—"?(*it).second?endl;

it++;

)

)

system("pause");

return0;

}

cTC:WIND0TS\syste>32\c>d.eze

Inputfamilies'name(ctrl+ztoend):

wans

InputchiIdren'snameandbirthday(ctrI+ztoend):

qian2.23

hui9.20

Inputfamilies'name(ctrl+ztoend):

hwang

InputchiIdren'snameandbirthday(ctrl+ztoend):

wei12.01

jiao2.14

kun10.08

'7

InputfamiIies'name(ctrl+ztoend):

;N

Inputafamilynametosearch:

wang

Thefamily'schiIdrenandeverychiId'sbirthdayis:

,qian——2.23

hui---9.20

,請按任意鍵繼續(xù)...

20.列出至少三種可以使用map類型的應(yīng)用。為每種應(yīng)用定義map對象,并指出如何插入和

讀取元素。

字典:map<string,string>dictionary;

電話簿:map<string,string>telBook;

超市物價表:map<string,double>priceList;

插入元素可以用:下標操作符或insert函數(shù);用find函數(shù)讀取元素。

21解釋map和set容器的差別,以及它們各自適用的情況。

差別:map容器是K-V對的集合,set容器是鍵的集合;map類型適用于需要了解鍵與

值的對應(yīng)情況,而set類型適用于只需判斷某值是否存在的情況。

22.解釋set和list容器的差別,以及它們各自適用的情況。

差別:set容器中的元素不能修改,而list容器中的元素可以修改;

set容器適用于保存元素值不變的集合,而list容器適用于保存會發(fā)生變化的元素。

23.編寫程序?qū)⑴懦膯卧~存儲在vector對象中,而不是存儲在set對象中。請指出使用set

的好處。

//ll.16_10.23_restricted_wc.cpp:定義控制臺應(yīng)用程序的入口點。

//

include"stdafx.h"

#include<iostream>

#include<string>

#include<utility>

#include<vector>

#include<set>

#include<map>

usingnamespacestd;

voidrestricted_wc(vector<string>strVec,map<string,int>&wordCount)

(

//createasetofexcludedwords

set<string>excluded;

for(vector<string>::iteratorit=strVec.begin();it!=strVec.end();++it)

(

excluded.insert(*it);

)

stringword;

cout?"InputsomewordstocountthewordsinwordCount(map)(Ctrl+ztoend):

?endl;

cin.clear();

while(cin?word)

(

if(!excluded.count(word))

++wordCount[word];

)

)

int_tmain(intargc,_TCHAR*argv[])

(

cout?"Inputsomewordstovector<string>excluded(Ctrl+ztoend):"?endl;

vector<string>excludedVec;

stringexcludedWord;

while(cin?excludedWord)

excludedVec.push_back(excludedWord);

//userestricted_wc()

map<string,int>wordCount;

restricted_wc(excludedVec,wordCount);

//showoutthemap:wordCount

cout?"\n\tShowoutthemap:wordCount:"?endl;

for(map<string,int>::iteratorit=wordCount.begin();it!=wordCount.end();++it)

cout?"Theword?(*it).first?appearsfor"?(*it).second?"times."?

endl;

)

system("pause");

return0;

c\e:\hhv\hhvprogra>\11-16_10_23_restricted_wc\debug\11.16_10.23_restric..

Inputsomeviordstouector<string>excluded<Ctrl+ztoend):

Iantotheourmymeso,.?

人Z

InputsomewordstocountthewordsinviordCount<nap><Ctrl+ztoend〉:

hellofriend.

todayourschoolwillhauesonegueststocone.

rz

Showoutthenap:wordCount:

?cone9appears1tines.

?friend'appears1tines.

?guests*appears1times.

9haue'appears1tines.

hello'appears1times.

?school'appears1tines.

9some'appears1times.

?today9appears1tines.

9will'appears1times.

清按任意鍵繼續(xù)...

24.編寫程序通過刪除單詞尾部的M生成單詞的非負數(shù)版本。同時,建立一個單詞排除集,

用于識別以號結(jié)尾,但這個結(jié)尾的M又不能刪除的單詞。例如,放在該排除集中的單詞可能

有success和class。使用這個排除集編寫程序,刪除輸入單詞的復(fù)數(shù)后綴,而如果輸入的是

排除集中的單詞,則保持該單詞不變。

//ll.16_10.25_exclude_s__of_words__wc.cpp:定義控制臺應(yīng)用程序的入口點。

//

#include"stdafx.h"

#include<iostream>

#include<string>

#include<set>

usingnamespacestd;

int_tmain(intargc,_TCHAR*argv[])

(

set<string>excluded;

//createsetofexcludedwords

excluded.insert("success");

excluded.insert("class");

//getridof's'

stringword;

cout?"\nInputsomewords:"?endl;

while(cin?word)

{

if(!excluded.count(word))

word.resize(word.size()-1);

cout?"\nNot-pluralversion:"?word?endl

?"\nEnteraword(ctrl+ztoend)"?endl;

)

system("pause");

return0;

cre:\hhv\hhvprogra*\11.16_10-25_

Inputsonewords:

takes

Not-pluraluersion:take

Enteraword<ctrl+ztoend>

success

Not-pluraluei*sion:success

Enteraword<ctrl+ztoend>

class

Not-pluraluersion:class

Enteraviord<ctrl+ztoend>

trees

Not-pluraluersion:tree

Enteraword<ctrl+ztoend>

善按任意鍵繼續(xù).?.

25.定義一個vector容器,存儲你在未來六個月要閱讀的書,再定義一個set,用于記錄你已

經(jīng)看過的書名。編寫程序從vector中為你選擇一本沒有讀過而現(xiàn)在要讀的書。當它為你返

回選中的書名后,應(yīng)該將該書名放入記錄已讀書目的set中。如果實際上你把這本書放在一

邊沒有看,則本程序應(yīng)該支持從己讀書目的set中刪除該書的記錄。在虛擬的六個月后,輸

出已讀書目和還沒有讀的書。

//ll.16_10.25_book_useVector_set.cpp:定義控制臺應(yīng)用程序的入口點。

//

#include"stdafx.h"

#include<iostream>

#include<string>

#include<vector>

#include<set>

#include<cstdlib>

#include<ctime>

usingnamespacestd;

int_tmain(intargc,_TCHAR*argv[])

{

//1createvector:bookVec

vector<string>strVecBook;

stringbName;

cout?"Inputbooks'nameyouwannaread(ctrl+ztoend):\n";

while(cin?bName)

strVecBook.push_back(bName);

size__tNumOfBooks=strVecBook.size();//recordnumberofbooks

//2createset:strSetReadedBook

set<string>strSetReadedBook;

stringstrChoice,bookName;

bool_6MonthLater=false;

//usesystem'stimeforseedofrand

srand((unsigned)time(NULL));

while(!_6MonthLater&&!strVecBook.empty())

{

cin.clear();

cout?"\n==?Doyouwannareadabook?(Yes/No):

cin?strChoice;

if(strChoice[0]=='Y'11strChoice[0]=='y')

(

inti=rand()%strVecBook.size();

bookName=strVecBook[i];

cout?"=?Wechoosethisbookforyou:“?bookName?endl;

strSetReadedBook.insert(bookName);

strVecBook.erase(strVecBook.begin()+i);

cout?"\tOnemonthlater......"?endl

?"Didyoureadthisbook?(Yes/No):

//cin.clear();

cin?strChoice;

if(strChoice[0]=='n'11strChoice[0]==*N')

(

//deletethebookfromstrSetReadedBookandaddtostrVecBook

strSetReadedBook.erase(bookName);

strVecBook.push_back(bookName);

)

)

//6monthlater?

cout?"6monthlater?(Yes/No):

//cin.clear();

cin?strChoice;

if(strChoice[0]=='Y*11strChoice[0]=='y')

_6MonthLater=true;

)

if(_6MonthLater)

{

if(IstrSetReadedBook.emptyO)

(

cout?"\n==?>Duringthelatest6months,youread:\n\t";

for(set<string>::iteratoriter=strSetReadedBook.begin();iter!=

strSetReadedBook.end();++iter)

(

cout?*iter?"

)

)

if(!strVecBook.empty())

(

cout?"\n==?>Thebooksyouhavenotread:\n\t";

for(vector<string>::iteratorit=strVecBook.begin();it!=strVecBook.end();++it)

(

cout?*it?"

)

)

cout?endl;

)

if(strSetReadedBook.size()==NumOfBooks)

cout?"\tGood,youreadallthebooks."?endl;

system("pause");

return0;

c<e:\hhv\hhvprogra>\l1.16_10.25_book_usevector_set\

Inputbooks'nameyouv/annaread<ctrl+ztoend>:

blb2b3b4

人Z

==>>Doyouwannareadabook?<Yes/No>:yes

=>>Wechoosethisbookforyou:b3

Onemonthlater......

Didyoureadthisbook?<Yes/No>:yes

6monthlater?<Yes/No>:no

==>>Doyouwannareadabook?<Yes/No>:yes

=>>Wechoosethisbookforyou:b4

Onemonthlater......

Didyoureadthisbook?<Yes/No>:no

6monthlater?<Yes/No>:no

==>>Doyoviwannareadabook?<Yes/No>:yes

=>>Wechoosethisbookforyou:b2

Onemonthlater......

Didyoureadthisbook?<Yes/No>:yes

6monthlater?<Yes/No>:yes

==>>>Duringthelatest6months.youread:

b2b3

==>>>Thebooksyouhauenotread:

blb4

請按任意鍵繼續(xù)???

26.編寫程序建立作者及其作品的multimap容器,使用find函數(shù)在multimap中查找元素,

并調(diào)用erase將其刪除。當所尋找的元素不存在時,確保你的程序依然能正確執(zhí)行。

//ll.16_10.26_multimap.cpp:定義控制臺應(yīng)用程序的入口點。

//

#include"stdafx.h"

#include<iostream>

#include<map>

#include<utility>

#include<string>

usingnamespacestd;

int__tmain(intargc,_TCHAR*argv[])

(

multimap<string,string>mmapAuthor;

stringauthor,book;

cout?"\t=?InputAuthorandhisBook(Ctrl+ztoend):\n";

while(cin?author?book)

mmapAuthor.insert(make_pair(author,book));

)

〃search

stringstrSearchltem;

cout?"\n\t=?Inputwhichauthordoyouwannasearch:

cin.clear();

cin?strSearchltem;

multimap<string,string>::iteratoriter=mmapAuthor.find(strSearchltem);

typedefmultimap<string,string>::size_typesz_type;

sz_typeamount=mmapAuthor.count(strSearchltem);

for(sz_typeent=0;ent!=amount;++cnt,++iter)

(

cout?"\n\tA_AWegottheauthor:"?iter->first?endl

?"\t=?hisbook:\t"?iter->second?endl;

}

//erase

amount=mmapAuthor.erase(strSearchltem);

if(amount)

(

cout?"\n\tWesuccessfullytoerase"?amount?"booksoftheauthor."?endl;

)

cout?endl;

system("pause");

return0;

c\e:\hhv\hh<progra>\l1.16_10.26_>ulti>ap\debug\l1.16_10-26_

=>>InputAuthorandhisBook<Ctrl+ztoend>:

]hhwC++_led

wwqC++_2ed

lihviCJL

wwqC_L_2ed

hwC_sharp

=>>Inputwhichauthordoyouwannasearch:hhw

入_人Wegottheauthor:hhv/

=>>hisbook:C++_led

人_人Wegottheauthor:hhvj

=>>hisbook:C」

人_人Wegottheauthor:hhv/

=>>hisbook:C_sharp

Wesuccessfullytoerase3booksoftheauthor.

情按任意鍵繼續(xù)...

27.重復(fù)上一題所編寫的程序,但這一次要求使用equal」ange函數(shù)獲取迭代器,然后刪除一

段范圍內(nèi)的元素。

//ll.16_10.27_equal_range.cpp:定義控制臺應(yīng)用程序的入口點。

//

#include"stdafx.h"

#include<iostream>

#include<map>

#include<utility>

#include<string>

usingnamespacestd;

int_tmain(intargc,_TCHAR*argv[])

(

multimap<string,string>mmapAuthor;

stringauthor,book;

cout?"\t=?InputAuthorandhisBook(Ctrl+ztoend):\n";

while(cin?author?book)

(

mmapAuthor.insert(make_pair(author,book));

)

//search

stringstrSearchltem;

cout?"\n\t=?Inputwhichauthordoyouwannasearch:

cin.clear();

cin?strSearchltem;

typedefmultimap<string,string>::size_typesz_type;

typedefmultimap<string,string>::iteratorauthorjt;

sz__typeamount=mmapAuthor.count(strSearchltem);

pair<authorjt,authorjt>pos=mmapAuthor.equal_range(strSearchltem);

authorjtit=pos.first;//recordtheiterator

while(it!=pos.second)

(

cout?"\n\tA_AWegottheauthor:"?it->first?endl

?"\t=?hisbook:\t"?it->second?endl;

++it;

}

//erase

mmapAuthor.erase(pos.first,pos.second);

if(amount)

cout?"\n\tWesuccessfullytoerase"?amount?"booksoftheauthor."?endl;

)

cout?"\n\t=?Nowthecontentofmultimapis:"?endl;

for(author_ititer=mmapAuthor.begin();iter!=mmapAuthor.end();++iter)

(

cout?iter->first?""?iter->second?endl;

)

cout?endl;

system("pause");

——■

Ic:C,MR

e:\hhv\hhvprogra>\11.,16_10.27_equal_range\debug\11.16_1

1=>>InputAuthorandhisBook<Ctrl+ztoend>:

C++

C++Priner

liihuC__plus

C__sharp

=>>Inputwhichauthordoyouwannasearch:v/wq

入_人Wegottheauthor:vjvjq

=>>hisbook:C++Priner

人一人Wegottheauthor:viv/q

=>>hisbook:C_sharp

Wesuccessfullytoerase2booksoftheauthor.

=>>Nowthecontentofmultimapis:

------------C++

----C__plus

*青按任意鍵繼續(xù)...

28.沿用上題中的multimap容器,編寫程序以下面的格式按姓名首字母的順序輸出作者名字:

AuthorNamesBginningwith'A':

Author,book,book,...

AuthorNamesBeginningwithB:

//11.16_10.28_multimap_Author_and_work.cpp:定義控制臺應(yīng)用程序的入口點。

//

#include"stdafx.h"

#include<iostream>

#include<map>

#include<utility>

#include<string>

usingnamespacestd;

int_tmain(intargc,_TCHAR*argv[])

(

multimap<string,string>mmapAuthor;

stringauthor,book;

cin.clear();

cout?"\t=?InputAuthorandhisBook(Ctrl+ztoend):\n";

while(cin?author?book)

(

mmapAuthor.insert(make_pair(author,book));

}

typedefmultimap<stringzstring>::iteratorauthorjt;

authorjtiter=mmapAuthor.begin();

if(iter==mmapAuthor.end())

(

cout?"\n\tEmptymultimap!"?endl;

return0;

)

stringcurrAuthor,preAuthor;

do

(

currAuthor=iter->first;

if(preAuthor.empty()||currAuthor[0]!=preAuthor[0])

(

cout?"AuthorNamesBeginningwith'"

?iter->first[O]?"':"?endl;

}

cout?currAuthor;

pair<authorjt,authorjt>pos=mmapAuthor.equal_range(iter->first);

while(pos.first!=pos.second)

(

cout?","?pos.first->second;

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
  • 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論