




版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
C++Primer中文版(第4版)(中英對照)四
PartII:ContainersandAlgorithms
第二部分:容器和算法
We'vesaidthatC++isaboutefficientprogrammingwithabstractions.TheStandardLibraryisa
goodexample:Thelibrarydefinesanumberofcontainerclassesandafamilyofgenericalgorithms
thatletuswriteprogramsthataresuccinct,abstract,andefficient.Thelibraryworriesabout
bookkeepingdetailsinparticular,takingcareofmemorymanagementsothatourprogramscanworry
abouttheactualproblemsweneedtosolve.
C++提供了使用抽象進行高效率編程的方式。標準庫就是一個很好的例子:標準庫定義了許多容器類以及一
系列泛型算法,使程序員可以更簡潔、抽象和有效地編寫程序。這樣可以讓標準庫操心那些繁瑣的細節,特
別是內存管理,我們的程序只需要關注要解決的實際問題就行了。
InChapter3weintroducedthevectorcontainertype.We'11learnmoreinChapter9aboutvector
andtheothersequentialcontainertypesprovidedbythelibrary.We'11alsocovermoreoperations
providedbythestringtype.Wecanthinkofastringasaspecialkindofcontainerthatcontains
onlycharacters.Thestringtypesupportsmany,butnotall,ofthecontaineroperations.
第三章介紹了vector容器類型。我們將會在第九章進?步探討vector和其他順序容器類型,而且還會學
習string類型提供的更多操作,這些容器類型都是由標準庫定義的。我們可將string視為僅包含字符的
特殊容器,string類型提供大量(但并不是全部)的容器操作。
Thelibraryalsodefinesseveralassociativecontainers.Elementsinanassociativecontainerare
orderedbykeyratherthansequentially.Theassociativecontainerssharemanyoperationswith
thesequentialcontainersandalsodefineoperationsthatarespecifictotheassociative
containers.TheassociativecontainersarecoveredinChapter10.
標準庫還定義了兒種關聯容器。關聯容器中的元素不是順序排列,而是按鍵(key)排序的。關聯容器共享
了許多順序容器提供的操作,止匕外,還定義了自己特殊的操作。我們將在第十章學習相關的內容。
Chapter11introducesthegenericalgorithms.Thealgorithmstypicallyoperateonarangeof
elementsfromacontainerorothersequence.Thealgorithmslibraryoffersefficient
implementationsofvariousclassicalalgorithms,suchassearching,sorting,andothercommon
tasks.Forexample,thereisacopyalgorithm,whichcopieselementsfromonesequencetoanother;
find,whichlooksforagivenelement;andsoon.Thealgorithmsaregenericintwoways:They
theycanbeappliedtodifferentkindsofcontainers,andthosecontainersmaycontainelements
ofmosttypes.
第十?章介紹了泛型算法,這些算法通常作用于容器或序列中某一范圍的元素。算法庫提供了各種各樣經典
算法的有效實現,像查找、排序及其他常見的算法任務。例如,復制算法將一個序列中所有所元素復制到另
一個序列中;查找算法則用于尋找一個指定元素,等等。泛型算法中,所謂“泛型(generic)”指的是兩
個方面:這些算法可作用于各種不同的容器類型,而這些容器乂可以容納多種不同類型的元素。
Thelibraryisdesignedsothatthecontainertypesprovideacommoninterface:Iftwocontainers
offerasimilaroperation,thenthatoperationwi11bedefinedidenticallyforbothcontainers.
Forexample,allthecontainershaveanoperationtoreturnthenumberofelementsinthecontainer.
Allthecontainersnamethatoperationsize,andtheyalldefineatypenamedsizetypethatis
thetypeofthevaluereturnedbysize.Similarly,thealgorithmshaveaconsistentinterface.
Forexample,mostalgorithmsoperateonarangeofelementsspecifiedbyapairofiterators.
為容器類型提供通用接口是設計庫的目的。如果兩種容器提供相似的操作,則為它們定義的這個操作應該完
全相同。例如,所有容器都有返回容器內元素個數的操作,于是所有容器都將操作命名為size,并將size返
同值的類型都指定為size_type類型。類似地,算法具有一致的接口。例如,大部分算法都作用在由一對
迭代器指定的元素范圍上。
Becausethecontaineroperationsandalgorithmsaredefinedconsistently,learningthelibrary
becomeseasier:Onceyouunderstandhowanoperationworks,youcanapplythatsameoperationto
othercontainers.Moreimportantly,thiscommonalityofinterfaceleadstomoreflexibleprograms.
Itisoftenpossibletotakeaprogramwrittentouseoneconteiinertypeandchangeittousea
differentcontainerwithouthavingtorewritecode.Aswe’11see,thecontainersofferdifferent
performancetradeoffs,andtheabilitytochangecontainertypescanbevaluablewhenfine-tuning
theperformanceofasystem.
容器提供的操作和算法是一致定義的,這使得學習標準庫更容易:只需理解一個操作如何工作,就能將該操
作應用于其他的容器。更重要的是,接口的?致性使程序變得更靈活。通常不需要重新編寫代碼,就可以將
一段使用某種容器類型的程序修改為使用不同容器實現。正如我們所看到的,容器提供了不同的性能折衷方
案,可以改變容器類型對優化系統性能來說頗有價值。
CONTENTS
目錄
Chapter9SequentialContainers
Chapter10AssociativeContainers
Chapter11GenericAlgorithms
Chapter9.SequentialContainers
CONTENTS
目錄
Seclion9.1DefiningaSequentialContainer307
Seelion9.2IteratorsandIteratorRanges311
SQgiiop9.3SequenceContainerOperations316
Scc[iQp9.4HowavectorGrows330
Section9.5DecidingWhichContainertoUse333
Section9.6stringsRevisited335
Section9.7ContainerAdaptors348
ChapterSummary353
DefinedTerms353
Thischaptercompletesourdiscussionofthestandard-1ibrarysequentialcontainertypes.It
expandsonthematerialfromChaplcr3,whichintroducedthemostcommonlyusedsequential
container,thevectortype.Elementsinasequentialcontainerarestoredandaccessedbyposition.
Thelibraryalsodefinesseveralassociativecontainers,whichholdelementswhoseorderdepends
onakey.Associativecontainersarecoveredinthenextchapter.
第二堂介紹了最常用的順序容器:vector類型。本章將對第三章的內容進行擴充和完善,繼續討論標準庫
提供的順序容器類型。順序容器內的元素按其位置存儲和訪問。除順序容器外,標準庫還定義了兒種關聯容
器,其元素按鍵(key)排序。我們將在下一章討論它們。
Thecontainerclassesshareacommoninterface.Thisfactmakesthelibraryeasiertolearn;what
welearnaboutonetypeappliestoanother.Eachcontainertypeoffersadifferentsetoftime
andfunctionalitytradeoffs.Oftenaprogramusingonetypecanbefine-tunedbysubstituting
anothercontainerwithoutchangingourcodebeyondtheneedtochangetypedeclarations.
容器類共享公共的接口,這使標準庫更容易學習,只要學會其中一種類型就能運用另種類型。每種容器類
型提供一組不同的時間和功能折衷方案。通常不需要修改代碼,只需改變類型聲明,用一種容器類型替代另
一種容器類型,就可以優化程序的性能。
Acontainerholdsacollectionofobjectsofaspecifiedtype.We'veusedonekindofcontainer
already:thelibraryvectortype.Itisasequentialcontainer.Itholdsacollectionofelements
ofasingletype,makingitacontainer.Thoseelementsarestoredandaccessedbyposition,making
itasequentialcontainer.Theorderofelementsinasequentialcontainerisindependentofthe
valueoftheelements.Instead,theorderisdeterminedbytheorderinwhichelementsareadded
tothecontainer.
容器容納特定類型對象的集合。我們已經使用過種容器類型:標準庫vector類型,這是種順序容器
(sequentialcontainer)°它將單一類型元素聚集起來成為容器,然后根據位置來存儲和訪問這些元素,
這就是順序容器。順序容器的元素排列次序與元素值無關,而是由元素添加到容器里的次序決定。
The1ibrarydefinesthreekindsofsequentialcontainers:vector,list,anddeque(shortfor
“double-endedqueue“andpronounced"deck").Thesetypesdifferinhowelementsareaccessedand
therelativerun-timecostofaddingorremovingelements.The1ibraryalsoprovidesthreecontainer
adaptors.Effectively,anadaptoradaptsanunderlyingcontainertypebydefininganewinterface
intermsoftheoperationsprovidedbytheoriginaltype.Thesequentialcontaineradaptorsare
stack,queue,andpriorityqueue.
標準庫定義了三種順序容器類型:vector、list和deque(是雙端隊列"double-endedqueue”的簡寫,
發音為“deck”)。它們的差別在于訪問元素的方式,以及添加或刪除元素相關操作的運行代價。標準庫還
提供了三種容器適配器(adaptors)0實際上,適配器是根據原始的容器類型所提供的操作,通過定義新的
操作接口,來適應基礎的容器類型。順序容器適配器包括stack.queue和priorityqueue類型,見表一91。
Containersdefineonlyasmallnumberofoperations.Manyadditionaloperationsareprovidedby
thealgorithmslibrary,whichwe'11coverinChapter11.Forthoseoperationsthataredefined
bythecontainers,thelibraryimposesacommoninterface.Thecontainersvaryastowhich
operationstheyprovide,butiftwocontainersprovidethesameoperation,thentheinterface(name
andnumberofarguments)willbethesameforbothcontainertypes.Thesetofoperationsonthe
containertypesformakindofhierarchy:
容器只定義了少量操作。大多數額外操作則由算法庫提供,我們將在第十?章學習算法庫。標準庫為由容器
類型定義的操作強加了公共的接口。這些容器類型的差別在于它們提供哪些操作,但是如果兩個容器提供了
相同的操作,則它們的接口(函數名字和參數個數)應該相同。容器類型的操作集合形成了以下層次結構:
?Someoperationsaresupportedbyal1containertypes.
一些操作適用于所有容器類型。
?Otheroperationsarecommontoonlythesequentialoronlytheassociativecontainers.
另外一些操作則只適用于順序或關聯容器類型。
?Stillothersarecommontoonlyasubsetofeitherthesequentialorassociativecontainers.
還有一些操作只適用于順序或關聯容器類型的個子集。
Intheremainderofthischapter,welookatthesequentialcontainertypesandtheiroperations
indetail.
在本章的后續部分,我們將詳細描述順序容器類型和它們所提供的操作。
表9.L順序容器類型
Table9.1.SequentialContainerTypes
SequentialContainers
順序容器
vectorSupportsfastrandomaccess
支持快速隨機訪問
listSupportsfastinsertion/deletion
支持快速插入/刪除
dequeDouble-endedqueue
雙端隊列
SequentialContainerAdaptors
順序容器適配器
stackLastin/Firstoutstack
后進先出(LIFO)堆棧
queueFirstin/Firstoutqueue
先進先出(FIFO)隊列
priorityqueuePriority-managedqueue
有優先級管理的隊列
9.1.DefiningaSequentialContainer
9.1.順序容器的定義
Wealreadyknowafairbitabouthowtousethesequentialcontainersbasedonwhatwecovered
inSection3.3(p.90).Todefineacontainerobject,wemustincludeitsassociatedheaderfile,
whichisoneof
在第3.3節中,我們已經了解了一些使用順序容器類型的知識。為了定義一個容器類型的對象,必須先包
含相關的頭文件,即下列頭文件之一:
#include<vector>
#include<list>
#include<deque>
Eachofthecontainersisaclasstemplate(Section3.3,p.90).Todefineaparticularkindof
container,wenamethecontainerfollowedbyanglebracketsthatenclosethetypeoftheelements
thecontainerwillhold:
所有的容器都是類模板(第3.3節)o要定義某種特殊的容器,必須在容器名后加一對尖括號,尖括號里
面提供容器中存放的元素的類型:
vector<string>svec;//emptyvectorthatcanholdstrings
list<int>ilist;//emptylistthatcanholdints
deque<Sales_item>items;//emptydequethatholdsSales_items
Eachcontainerdefinesadefaultconstructorthatcreatesanemptycontainerofthespeicfiedtype.
Recallthatadefaultconstructortakesnoarguments.
所有容器類型都定義了默認構造函數,用于創建指定類型的空容器對象。默認構造函數不帶參數。
Forreasonsthatshallbecomeclearshortly,themostcommonlyusedcontainer
constructoristhedefaultconstructor.Inmostprograms,usingthedefault
constructorgivesthebestrun-timeperformanceandmakesusingthecontainer
easier.
為了使程序更清晰、簡短,容器類型最常用的構造函數是默認構造函數。在大多數的程
序中,使用默認構造函數能達到最佳運行時性能,并且使容器更容易使用。
9.1.1.InitializingContainerElements
9.1.1.容器元素的初始化
Inadditiontodefiningadefaultconstructor,eachcontainertypealsosupportsconstructorsthat
allowustospecifyinitialelementvalues.
除了默認構造函數,容器類型還提供其他的構造函數,使程序員可一以指定元素初值,見表9.2。
表9.2.容器構造函數
Table9.2.ContainerCreateanemptycontainernamedc.Cisacontainernagsuchasvector,
ConstructorsandTistheelementtype,suchasintorstring.Validforallcontainers.
C<T>c;創建一個名為c的空容器。C是容器類型名,如vector,T是元素類型,如int或
string適用于所有容器。
Cc(c2);Createcasacopyofcontainerc2;candc2mustbethesamecontainertype
andholdvaluesofthesametype.Validforallcontainers.
創建容器c2的副本c;c和c2必須具有相同的容器類型,并存放相同類型的元
素。適用于所有容器。
Cc(b,e);Createcwithacopyoftheelementsfromtherangedenotedbyiteratorsb
ande.Validforallcontainers.
創建c,其元素是迭代器b和e標示的范圍內元素的副本。適用于所有容器。
Cc(n,t);Createcwithnelements,eachwithvaluet,whichmustbeavalueofthe
elementtypeofCoratypeconvertibletothattype.
用n個值為l的元素創建容器c,其中值t必須是容器類型C的元素類型的值,
或者是可轉換為該類型的值。
Sequentialcontainersonly.
只適用于順序容器
Cc(n);Createcwithnvalue-initialized(Section3.3.1,p.92)elements.
創建有n個值初始化(第3.3.1節)(value-initialized)元素的容器c0
Sequentialcontainersonly.
只適用于順序容器
IntializingaContainerasaCopyofAnotherContainer
將一個容器初始化為另一個容器的副本
Whenweinitializeasequentialcontainerusinganyconstructorotherthanthedefaultconstructor,
wemustindicatehowmanyelementsthecontainerwillhave.Wemustalsosupplyinitialvalues
forthoseelements.Onewaytospecifyboththesizeandelement,valuesistoinitializeanew
containerasacopyofanexistingcontainerofthesametype:
當不使用默認構造函數,而是用其他構造函數初始化順序容器時,必須指出該容器有多少個元素,并提供這
當元素的初值。同時指定元素個數和初值的?個方法是將新創建的容器初始化為?個同類型的已存在容器的
副本:
vector<int>ivec;
vector<int>ivec2(ivec);//ok:ivecisvector<int>
list<int>ilist(ivec);//error:ivecisnotlist<int>
vector<double>dvec(ivec);//error:ivecholdsintnotdouble
Whenwecopyonecontainerintoanother,thetypesmustmatchexactly:The
containertypeandelementtypemustbethesame.
將一個容器復制給另一個容器時,類型必須匹配:容器類型和元素類型都必須相同。
InitializingasaCopyofaRangeofElements
初始化為一段元素的副本
Althoughwecannotcopytheelementsfromonekindofcontainertoanotherdirectly,wecando
soindirectlybypassingapairofiterators(Section3.4,p.95).Whenweuseiterators,there
isnorequirementthattheconteiinertypesbeidentical.Theelementtypesinthecontainerscan
differaslongastheyarecompatible.Itmustbepossibletoconverttheelementwecopyinto
thetypeheldbythecontainerweareconstructing.
盡管不能宜接將?種容器內的元素復制給另?種容器,但系統允許通過傳遞,對迭代器(第3.4甘)間接
實現該實現該功能。使用迭代器時,不要求容器類型相同。容器內的元素類型也可以不相同,只要它們相互
兼容,能夠將要復制的元素轉換為所構建的新容器的元素類型,即可實現復制。
Theiteratorsdenotearangeofelementsthatwewanttocopy.Theseelementsareusedtoinitialize
theelementsofthenewcontainer.Theiteratorsmarkthefirstandonepastthelastelementto
becopied.Wecanusethisformofinitializationtocopyacontainerthatwecouldnotcopydirectly.
Moreimportantly,wecanuseittocopyonlyasubsequenceoftheothercontainer:
迭代器標記了要復制的元素范圍,這些元素用于初始化新容器的元素。迭代器標記出要復制的第一個元素和
最后個元素。采用這種初始化形式可復制不能直接復制的容器。更重要的是,可以實現復制其他容器的一
個子序列:
//initializeslistwithcopyofeachelementofsvec
list<string>slist(svec.beginO,svec.end());
//findmidpointinthevector
vector<string>::iteratormid=svec.beginO+svec.size()/2;
//initializefrontwithfirsthalfofsvec:Theelementsuptobutnotincluding*mid
deque<string>front(svec.begin(),mid);
//initializebackwithsecondhalfofsvec:Theelements*midthroughendofsvec
deque<string>back(mid,svec.end());
Recallthatpointersareiterators,soitshouldnotbesurprisingthatwecaninitializeacontainer
fromapairofpointersintoabuilt-inarray:
回顧一下指針,我們知道指針就是迭代器,因此允許通過使用內置數組中的一對指針初始化容器也就不奇怪
了:
char*words[]={"stately”,〃plump〃,〃buck〃,“mulligan"};
//calculatehowmanyelementsinwords
size_twords_size=sizeof(words)/sizeof(char*);
//useentirearraytoinitializewords2
list<string>words2(words,words+words_size);
Hereweusesizeof(Section5.8,p.167)tocalculatethesizeofthearray.Weaddthatsizeto
apointertothefirstelementtogetapointertoalocationonepasttheendofthearray.The
initializersforwords2areapointertothefirstelementinwordsandasecondpointeronepast
thelastelementinthatarray.Thesecondpointerservesasastoppingcondition;thelocation
itaddressesisnotincludedintheelementstobecopied.
這里,使用sizeof(5.8節)計算數組的長度。將數組長度加到指向第一個元素的指針上就可以得到指向
超出數組末端的下一位置的指針。通過指向第一個元素的指針words和指向數組中最后?個元素的下?位
置的指針,實現了words2的初始化。其中第二個指針提供停止復制的條件,其所指向的位置上存放的元素
并沒有復制。
AllocatingandInitializingaSpecifiedNumberofElements
分配和初始化指定數目的元素
Whencreatingasequentialcontainer,wemayspecifyanexplicitsizeandan(optional)initializer
tousefortheelements.Thesizecanbeeitheraconstantornon-constantexpression.Theelement
initializermustbeavalidvaluethatcanbeusedtoinitializeanobjectoftheelementtype:
創建順序容器時,可顯式指定容器大小和?個(可選的)元素初始化式。容器大小可以是常量或非常量表達
式,元素初始化則必須是可用于初始化其元素類型的對象的值:
constlist<int>::size_typelistsize=64;
list<string>slist(list_size,〃eh?〃);//64strings,eachiseh?
Thiscodeinitializesslisttohave64elements,eachwiththevalueeh?.
這段代碼表示slist含有64個元素,每個元素都被初始化為“eh?”字符串。
Asanalternativetospecifyingthenumberofelementsandanelementinitializer,wecanalso
specifyonlythesize:
創建容器時,除了指定元素個數,還可選擇是否提供元素初始化式。我們也可以只指定容器大小:
list<int>ilist(list_size);//64elements,eachinitializedto0
//svechasasmanyelementsasthereturnvaluefromget_word_count
externunsignedgetwordcount(conststring&fi1ename);
vector<string>svec(getwordcounl("Chimera"));
Whenwedonotsupplyanelementinitializer,thelibrarygeneratesavalue^initialized(Section
3.3.1,p.92)oneforus.Tousethisformofinitialization,theelementtypemusteitherbea
built-inorcompoundtypeorbeaclasstypethathasadefaultconstructor.Iftheelementtype
doesnothaveadefaultconstructor,thenanexplicitelementinitializermustbespecified.
不提供元素初始化式時,標準庫將為該容器實現值初始化(3.3.l&nbps;jn。采用這種類型的初始化,元
素類型必須是內置或復合類型,或者是提供了默認構造函數的類類型。如果元素類型沒有默認構造函數,則
必須顯式指定其元素初始化式。
Theconstructorsthattakeasizearevalidonlyforsequentialcontainers;they
arenotsupportedfortheassociativecontainers,
接受容器大小做形參的構造函數只適用于順序容器,而關聯容器不支持這種初始化。
ExercisesSection9.1.1
ExerciseExplainthefollowinginitializations.Indicateifanyareinerror,and
9.1:ifso,why,
解釋下列初始化,指出哪些是錯誤的,為什么?
intia[7]={0,1,172,3,5,8};
stringsa[6]={
“ForiSumter","Manassas","Perryville”,
“Vicksburg","Meridian","Chancellorsvilie*};
(a)vector<string>svec(sa,sa+6);
(b)list<int>ilist(ia+4,ia+6);
(c)vector<int>ivec(ia,ia+8);
(d)list<string>siist(sa+6,sa);
ExerciseShowanexampleofeachofthefourwaystocreateandinitializeavector.
9.2:Explainwhatvalueseachvectorcontains.
創建和初始化一個vector對象有4種方式,為每種方式提供一個例子,并解
釋每個例子生成的vector對象包含什么值。
ExerciseExplainthedifferencesbetweentheconstructorthattakesacontainer
9.3:tocopyandtheconstructorthattakestwoiterators.
解釋夏制容器對象的構造函數和使用兩個迭代器的構造函數之間的差別。
9.1.2.ConstraintsonTypesthataContainerCanHold
9.1.2.容器內元素的類型約束
Whilemosttypescanbeusedastheelementtypeofacontainer,therearetwoconstraintsthat
elementtypesmustmeet:
C++語言中,大多數類型都可用作容器的元素類型。容器元素類型必須滿足以下兩個約束:
?Theelementtypemustsupportassignment.
元素類型必須支持賦值運算。
?Wemustbeabletocopyobjectsoftheelementtype.
元素類型的對象必須可以復制。
Thereareadditionalconstraintsonthetypesusedasthekeyinanassociativecontainer,which
we'11coverinChapter10.
此外,關聯容器的鍵類型還需滿足其他的約束,我們將在第十章介紹相關內容。
Mosttypesmeettheseminimalelementtyperequirements.Allofthebuilt-inorcompoundtypes,
withtheexceptionofreferences,canbeusedastheelementtype.Referencesdonotsupport
assignmentinitsordinarymeaning,sowecannothavecontainersofreferences.
大多數類型滿足上述最低限度的元素類型要求。除了引用類型外,所有內置或復合類型都可用做元素類型。
引用不支持一般意義的賦值運算,因此沒有元素是引用類型的容器。
Withtheexceptionofthe10librarytypes(andtheautoptrtype,whichwecoverinSection17.1.9
(p.702)),allthelibrarytypesarevalidcontainerelementtypes.Inparticular,containers
themselvessatisfytheserequirements.Wecandefinecontainerswithelementsthatarethemselves
containers.OurSales_itemtypealsosatisifestheserequirements.
除輸入輸出(10)標準庫類型(以及第17.1.9節介紹的auto_ptr類型)之外,所有其他標準庫類型都是
有效的容器元素類型。特別地,容器本身也滿足上述要求,因應,可以定義元素本身就是容器類型的容器。
Sales_item類型也滿足上述要求。
The10librarytypesdonotsupportcopyorassignment.Therefore,wecannothaveacontainerthat
holdsobjectsofthe10types.
10庫類型不支持復制或賦值。因此,不能創建存放10類型對象的容器。
ContainerOperationsMayImposeAdditionalRequirements
容器操作的特殊要求
Therequirementtosupportcopyandassignmentistheminimalrequirementonelementtypes.In
addition,somecontaineroperationsimposeadditionalrequirementsontheelementtype.Ifthe
elementtypedoesn'tsupporttheadditionalrequirement,thenwecannotperformthatoperation:
Wecandefineacontainerofthattypebutmaynotusethatparticularoperation.
支持復制和賦值功能是容器元素類型的最低要求。此外,一些容器操作對元素類型還有特殊要求。如果元素
類型不支持這些特殊要求,則相關的容器操作就不能執行:我們可以定義該類型的容器,但不能使用某些特
定的操作。
Oneexampleofanoperationthatimposesatypeconstraintistheconstructorsthattakeasingle
initializerthatspecifiesthesizeofthecontainer.Ifourcontainerholdsobjectsofaclass
type,thenwecanusethisconstructoronlyiftheelementtypehasadefaultconstructor.Most
typesdohaveadefaultconstructor,althoughtherearesomeclassesthatdonot.Asanexample,
assumethatFooisaclassthatdoesnotdefineadefaultconstructorbutthatdoeshaveaconstructor
thattakesanintargument.Now,considerthefollowingdeclarations:
其中?種需外加類型要求的容器操作是指定容器大小并提供單個初始化式的構造函數。如果容器存儲類類型
的對象,那么只有當其元素類型提供默認構造函數時,容器才能使用這種構造函數。盡管有一些類沒有提供
默認構造函數,但大多數類類型都會有。例如,假設類Foo沒有默認構造函數,但提供了需要?個int型
形參的構造函數。現在,考慮下面的聲明:
vector<Foo>empty;//ok:noneedforelementdefaultconstructor
vector<Foo>bad(10);//error:nodefaultconstructorforFoo
vector<Foo>ok(10,1);//ok:eachelementinitializedto1
WecandefineanemptycontainertoholdFooobjects,butwecandefineoneofagivensizeonly
ifwealsospecifyaninitializerforeachelement.
我們定義一個存放Foo類型對象的空容器,但是,只有在同時指定每個元素的初始化式時,才能使用給定
容器大小的構造函數來創建同類型的容器對象。
Aswedescribethecontaineroperations,we'11notetheconstraints,ifany,thateachcontainer
operationplacesontheelementtype.
在描述容器操作時,我們應該留意(如果有的話)每個操作對元素類型的約束。
ContainersofContainers
容器的容器
Becausethecontainersmeettheconstraintsonelementtypes,wecandefineacontainerwhose
elementtypeisitselfacontainertype.Forexample,wemightdefinelinesasavectorwhose
elementsareavectorofstrings:
因為容器受容器元素類型的約束,所以可定義元素是容器類型的容器。例如,可以定義vector類型的容器
lines,其元素為string類型的vector對象:
//notespacing:use〃〉>〃not〃>〉〃whenspecifyingacontainerelementtype
vector<vector<string>>lines;//vectorofvectors
Notethespacingusedwhenspecifyingacontainerelementtypeasacontainer:
注意,在指定容器元素為容器類型時,必須如下使用空格:
vector<vector<string>>lines;//ok:spacerequiredbetweenclose>
vector<vector<string>>lines;//error:>>treatedasshiftoperator
Wemustseparatethetwoclosing>symbolswithaspacetoindicatethatthese
twocharactersrepresenttwosymbols.Withoutthespace,>>istreatedasasingle
symbol,therightshiftoperator,andresultsinacompile-timeerror.必須用
空格隔開兩個相鄰的>符號,以示這是兩個分開的符號,否則,系統會認為?是單
個符號,為右移操作符,并導致編譯時錯誤。
ExercisesSection9.1.2
ExerciseDefinealistthatholdselementsthataredequesthatholdints.
9.4:
定義一個list對象來存儲deque對象里的元素,該deque對象存放int型
兀素。
ExerciseWhycanwenothavecontainersthatholdiostreatnobjects?
9.5:
為什么我們不可以使用容器來存儲iostream對象?
ExerciseGivenaclasstypenamedFoothatdoesnotdefineadefaultconstructor
9.6:butdoesdefineaconstructorthattakesintvalues,definealistofFoo
thatholds10elements.
假設有個名為Foo的類,這個類沒有定義默認構造函數,但提供了需要個
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經權益所有人同意不得將文件中的內容挪作商業或盈利用途。
- 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
- 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025-2030中國波輪洗衣機行業市場深度調研及投資策略與投資前景預測研究報告
- 2025至2030年中國開口西瓜子行業投資前景及策略咨詢研究報告
- DB32/T 3738-2020食品安全電子追溯公眾查詢信息規范
- DB32/T 3594-2019晶體硅太陽電池熱斑耐久性能試驗方法
- DB32/T 3576-2019農村產權交易場所建設與管理
- DB32/T 3547-2019醫療機構廢水處理及在線監測技術規范
- DB32/T 3501-2019大規模教育考試網上評卷技術規范
- DB32/T 3495-2019普通國省道限制速度標志設置規范
- DB32/T 2887-2016曳引電梯鋼絲繩電磁檢測方法
- DB32/T 1248-2019番茄‘蘇粉8號、蘇粉11號’早春栽培技術規程
- 文明考風 誠信考試
- 《工程建設標準強制性條文》-20220326155703
- 價值型銷售(技能篇)
- 2024年浙江省單獨考試招生文化課考試數學試卷真題(含答案詳解)
- HSE管理體系與保證措施
- 人音版 三年級下冊《搖船調》教案
- 廣東省廣州大學附中2021-2022年初二12月大聯盟物理在線考試題
- 醫保政策培訓知識普及課件
- 小學四年級語文知識競賽(含答案)
- 人教版數學八年級下冊一次函數綜合大題練習
- 成語故事一箭雙雕
評論
0/150
提交評論