c primer中文版(第4版)(中英對照)4_第1頁
c primer中文版(第4版)(中英對照)4_第2頁
c primer中文版(第4版)(中英對照)4_第3頁
c primer中文版(第4版)(中英對照)4_第4頁
c primer中文版(第4版)(中英對照)4_第5頁
已閱讀5頁,還剩207頁未讀, 繼續(xù)免費閱讀

下載本文檔

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

文檔簡介

C++Primer中文版(第4版)(中英對照)四

PartII:ContainersandAlgorithms

第二部分:容器和算法

We'vesaidthatC++isaboutefficientprogrammingwithabstractions.TheStandardLibraryisa

goodexample:Thelibrarydefinesanumberofcontainerclassesandafamilyofgenericalgorithms

thatletuswriteprogramsthataresuccinct,abstract,andefficient.Thelibraryworriesabout

bookkeepingdetailsinparticular,takingcareofmemorymanagementsothatourprogramscanworry

abouttheactualproblemsweneedtosolve.

C++提供了使用抽象進行高效率編程的方式。標準庫就是一個很好的例子:標準庫定義了許多容器類以及一

系列泛型算法,使程序員可以更簡潔、抽象和有效地編寫程序。這樣可以讓標準庫操心那些繁瑣的細節(jié),特

別是內(nèi)存管理,我們的程序只需要關(guān)注要解決的實際問題就行了。

InChapter3weintroducedthevectorcontainertype.We'11learnmoreinChapter9aboutvector

andtheothersequentialcontainertypesprovidedbythelibrary.We'11alsocovermoreoperations

providedbythestringtype.Wecanthinkofastringasaspecialkindofcontainerthatcontains

onlycharacters.Thestringtypesupportsmany,butnotall,ofthecontaineroperations.

第三章介紹了vector容器類型。我們將會在第九章進?步探討vector和其他順序容器類型,而且還會學(xué)

習string類型提供的更多操作,這些容器類型都是由標準庫定義的。我們可將string視為僅包含字符的

特殊容器,string類型提供大量(但并不是全部)的容器操作。

Thelibraryalsodefinesseveralassociativecontainers.Elementsinanassociativecontainerare

orderedbykeyratherthansequentially.Theassociativecontainerssharemanyoperationswith

thesequentialcontainersandalsodefineoperationsthatarespecifictotheassociative

containers.TheassociativecontainersarecoveredinChapter10.

標準庫還定義了兒種關(guān)聯(lián)容器。關(guān)聯(lián)容器中的元素不是順序排列,而是按鍵(key)排序的。關(guān)聯(lián)容器共享

了許多順序容器提供的操作,止匕外,還定義了自己特殊的操作。我們將在第十章學(xué)習相關(guān)的內(nèi)容。

Chapter11introducesthegenericalgorithms.Thealgorithmstypicallyoperateonarangeof

elementsfromacontainerorothersequence.Thealgorithmslibraryoffersefficient

implementationsofvariousclassicalalgorithms,suchassearching,sorting,andothercommon

tasks.Forexample,thereisacopyalgorithm,whichcopieselementsfromonesequencetoanother;

find,whichlooksforagivenelement;andsoon.Thealgorithmsaregenericintwoways:They

theycanbeappliedtodifferentkindsofcontainers,andthosecontainersmaycontainelements

ofmosttypes.

第十?章介紹了泛型算法,這些算法通常作用于容器或序列中某一范圍的元素。算法庫提供了各種各樣經(jīng)典

算法的有效實現(xiàn),像查找、排序及其他常見的算法任務(wù)。例如,復(fù)制算法將一個序列中所有所元素復(fù)制到另

一個序列中;查找算法則用于尋找一個指定元素,等等。泛型算法中,所謂“泛型(generic)”指的是兩

個方面:這些算法可作用于各種不同的容器類型,而這些容器乂可以容納多種不同類型的元素。

Thelibraryisdesignedsothatthecontainertypesprovideacommoninterface:Iftwocontainers

offerasimilaroperation,thenthatoperationwi11bedefinedidenticallyforbothcontainers.

Forexample,allthecontainershaveanoperationtoreturnthenumberofelementsinthecontainer.

Allthecontainersnamethatoperationsize,andtheyalldefineatypenamedsizetypethatis

thetypeofthevaluereturnedbysize.Similarly,thealgorithmshaveaconsistentinterface.

Forexample,mostalgorithmsoperateonarangeofelementsspecifiedbyapairofiterators.

為容器類型提供通用接口是設(shè)計庫的目的。如果兩種容器提供相似的操作,則為它們定義的這個操作應(yīng)該完

全相同。例如,所有容器都有返回容器內(nèi)元素個數(shù)的操作,于是所有容器都將操作命名為size,并將size返

同值的類型都指定為size_type類型。類似地,算法具有一致的接口。例如,大部分算法都作用在由一對

迭代器指定的元素范圍上。

Becausethecontaineroperationsandalgorithmsaredefinedconsistently,learningthelibrary

becomeseasier:Onceyouunderstandhowanoperationworks,youcanapplythatsameoperationto

othercontainers.Moreimportantly,thiscommonalityofinterfaceleadstomoreflexibleprograms.

Itisoftenpossibletotakeaprogramwrittentouseoneconteiinertypeandchangeittousea

differentcontainerwithouthavingtorewritecode.Aswe’11see,thecontainersofferdifferent

performancetradeoffs,andtheabilitytochangecontainertypescanbevaluablewhenfine-tuning

theperformanceofasystem.

容器提供的操作和算法是一致定義的,這使得學(xué)習標準庫更容易:只需理解一個操作如何工作,就能將該操

作應(yīng)用于其他的容器。更重要的是,接口的?致性使程序變得更靈活。通常不需要重新編寫代碼,就可以將

一段使用某種容器類型的程序修改為使用不同容器實現(xiàn)。正如我們所看到的,容器提供了不同的性能折衷方

案,可以改變?nèi)萜黝愋蛯?yōu)化系統(tǒng)性能來說頗有價值。

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類型。本章將對第三章的內(nèi)容進行擴充和完善,繼續(xù)討論標準庫

提供的順序容器類型。順序容器內(nèi)的元素按其位置存儲和訪問。除順序容器外,標準庫還定義了兒種關(guān)聯(lián)容

器,其元素按鍵(key)排序。我們將在下一章討論它們。

Thecontainerclassesshareacommoninterface.Thisfactmakesthelibraryeasiertolearn;what

welearnaboutonetypeappliestoanother.Eachcontainertypeoffersadifferentsetoftime

andfunctionalitytradeoffs.Oftenaprogramusingonetypecanbefine-tunedbysubstituting

anothercontainerwithoutchangingourcodebeyondtheneedtochangetypedeclarations.

容器類共享公共的接口,這使標準庫更容易學(xué)習,只要學(xué)會其中一種類型就能運用另種類型。每種容器類

型提供一組不同的時間和功能折衷方案。通常不需要修改代碼,只需改變類型聲明,用一種容器類型替代另

一種容器類型,就可以優(yōu)化程序的性能。

Acontainerholdsacollectionofobjectsofaspecifiedtype.We'veusedonekindofcontainer

already:thelibraryvectortype.Itisasequentialcontainer.Itholdsacollectionofelements

ofasingletype,makingitacontainer.Thoseelementsarestoredandaccessedbyposition,making

itasequentialcontainer.Theorderofelementsinasequentialcontainerisindependentofthe

valueoftheelements.Instead,theorderisdeterminedbytheorderinwhichelementsareadded

tothecontainer.

容器容納特定類型對象的集合。我們已經(jīng)使用過種容器類型:標準庫vector類型,這是種順序容器

(sequentialcontainer)°它將單一類型元素聚集起來成為容器,然后根據(jù)位置來存儲和訪問這些元素,

這就是順序容器。順序容器的元素排列次序與元素值無關(guān),而是由元素添加到容器里的次序決定。

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”的簡寫,

發(fā)音為“deck”)。它們的差別在于訪問元素的方式,以及添加或刪除元素相關(guān)操作的運行代價。標準庫還

提供了三種容器適配器(adaptors)0實際上,適配器是根據(jù)原始的容器類型所提供的操作,通過定義新的

操作接口,來適應(yīng)基礎(chǔ)的容器類型。順序容器適配器包括stack.queue和priorityqueue類型,見表一91。

Containersdefineonlyasmallnumberofoperations.Manyadditionaloperationsareprovidedby

thealgorithmslibrary,whichwe'11coverinChapter11.Forthoseoperationsthataredefined

bythecontainers,thelibraryimposesacommoninterface.Thecontainersvaryastowhich

operationstheyprovide,butiftwocontainersprovidethesameoperation,thentheinterface(name

andnumberofarguments)willbethesameforbothcontainertypes.Thesetofoperationsonthe

containertypesformakindofhierarchy:

容器只定義了少量操作。大多數(shù)額外操作則由算法庫提供,我們將在第十?章學(xué)習算法庫。標準庫為由容器

類型定義的操作強加了公共的接口。這些容器類型的差別在于它們提供哪些操作,但是如果兩個容器提供了

相同的操作,則它們的接口(函數(shù)名字和參數(shù)個數(shù))應(yīng)該相同。容器類型的操作集合形成了以下層次結(jié)構(gòu):

?Someoperationsaresupportedbyal1containertypes.

一些操作適用于所有容器類型。

?Otheroperationsarecommontoonlythesequentialoronlytheassociativecontainers.

另外一些操作則只適用于順序或關(guān)聯(lián)容器類型。

?Stillothersarecommontoonlyasubsetofeitherthesequentialorassociativecontainers.

還有一些操作只適用于順序或關(guān)聯(lián)容器類型的個子集。

Intheremainderofthischapter,welookatthesequentialcontainertypesandtheiroperations

indetail.

在本章的后續(xù)部分,我們將詳細描述順序容器類型和它們所提供的操作。

表9.L順序容器類型

Table9.1.SequentialContainerTypes

SequentialContainers

順序容器

vectorSupportsfastrandomaccess

支持快速隨機訪問

listSupportsfastinsertion/deletion

支持快速插入/刪除

dequeDouble-endedqueue

雙端隊列

SequentialContainerAdaptors

順序容器適配器

stackLastin/Firstoutstack

后進先出(LIFO)堆棧

queueFirstin/Firstoutqueue

先進先出(FIFO)隊列

priorityqueuePriority-managedqueue

有優(yōu)先級管理的隊列

9.1.DefiningaSequentialContainer

9.1.順序容器的定義

Wealreadyknowafairbitabouthowtousethesequentialcontainersbasedonwhatwecovered

inSection3.3(p.90).Todefineacontainerobject,wemustincludeitsassociatedheaderfile,

whichisoneof

在第3.3節(jié)中,我們已經(jīng)了解了一些使用順序容器類型的知識。為了定義一個容器類型的對象,必須先包

含相關(guān)的頭文件,即下列頭文件之一:

#include<vector>

#include<list>

#include<deque>

Eachofthecontainersisaclasstemplate(Section3.3,p.90).Todefineaparticularkindof

container,wenamethecontainerfollowedbyanglebracketsthatenclosethetypeoftheelements

thecontainerwillhold:

所有的容器都是類模板(第3.3節(jié))o要定義某種特殊的容器,必須在容器名后加一對尖括號,尖括號里

面提供容器中存放的元素的類型:

vector<string>svec;//emptyvectorthatcanholdstrings

list<int>ilist;//emptylistthatcanholdints

deque<Sales_item>items;//emptydequethatholdsSales_items

Eachcontainerdefinesadefaultconstructorthatcreatesanemptycontainerofthespeicfiedtype.

Recallthatadefaultconstructortakesnoarguments.

所有容器類型都定義了默認構(gòu)造函數(shù),用于創(chuàng)建指定類型的空容器對象。默認構(gòu)造函數(shù)不帶參數(shù)。

Forreasonsthatshallbecomeclearshortly,themostcommonlyusedcontainer

constructoristhedefaultconstructor.Inmostprograms,usingthedefault

constructorgivesthebestrun-timeperformanceandmakesusingthecontainer

easier.

為了使程序更清晰、簡短,容器類型最常用的構(gòu)造函數(shù)是默認構(gòu)造函數(shù)。在大多數(shù)的程

序中,使用默認構(gòu)造函數(shù)能達到最佳運行時性能,并且使容器更容易使用。

9.1.1.InitializingContainerElements

9.1.1.容器元素的初始化

Inadditiontodefiningadefaultconstructor,eachcontainertypealsosupportsconstructorsthat

allowustospecifyinitialelementvalues.

除了默認構(gòu)造函數(shù),容器類型還提供其他的構(gòu)造函數(shù),使程序員可一以指定元素初值,見表9.2。

表9.2.容器構(gòu)造函數(shù)

Table9.2.ContainerCreateanemptycontainernamedc.Cisacontainernagsuchasvector,

ConstructorsandTistheelementtype,suchasintorstring.Validforallcontainers.

C<T>c;創(chuàng)建一個名為c的空容器。C是容器類型名,如vector,T是元素類型,如int或

string適用于所有容器。

Cc(c2);Createcasacopyofcontainerc2;candc2mustbethesamecontainertype

andholdvaluesofthesametype.Validforallcontainers.

創(chuàng)建容器c2的副本c;c和c2必須具有相同的容器類型,并存放相同類型的元

素。適用于所有容器。

Cc(b,e);Createcwithacopyoftheelementsfromtherangedenotedbyiteratorsb

ande.Validforallcontainers.

創(chuàng)建c,其元素是迭代器b和e標示的范圍內(nèi)元素的副本。適用于所有容器。

Cc(n,t);Createcwithnelements,eachwithvaluet,whichmustbeavalueofthe

elementtypeofCoratypeconvertibletothattype.

用n個值為l的元素創(chuàng)建容器c,其中值t必須是容器類型C的元素類型的值,

或者是可轉(zhuǎn)換為該類型的值。

Sequentialcontainersonly.

只適用于順序容器

Cc(n);Createcwithnvalue-initialized(Section3.3.1,p.92)elements.

創(chuàng)建有n個值初始化(第3.3.1節(jié))(value-initialized)元素的容器c0

Sequentialcontainersonly.

只適用于順序容器

IntializingaContainerasaCopyofAnotherContainer

將一個容器初始化為另一個容器的副本

Whenweinitializeasequentialcontainerusinganyconstructorotherthanthedefaultconstructor,

wemustindicatehowmanyelementsthecontainerwillhave.Wemustalsosupplyinitialvalues

forthoseelements.Onewaytospecifyboththesizeandelement,valuesistoinitializeanew

containerasacopyofanexistingcontainerofthesametype:

當不使用默認構(gòu)造函數(shù),而是用其他構(gòu)造函數(shù)初始化順序容器時,必須指出該容器有多少個元素,并提供這

當元素的初值。同時指定元素個數(shù)和初值的?個方法是將新創(chuàng)建的容器初始化為?個同類型的已存在容器的

副本:

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.

將一個容器復(fù)制給另一個容器時,類型必須匹配:容器類型和元素類型都必須相同。

InitializingasaCopyofaRangeofElements

初始化為一段元素的副本

Althoughwecannotcopytheelementsfromonekindofcontainertoanotherdirectly,wecando

soindirectlybypassingapairofiterators(Section3.4,p.95).Whenweuseiterators,there

isnorequirementthattheconteiinertypesbeidentical.Theelementtypesinthecontainerscan

differaslongastheyarecompatible.Itmustbepossibletoconverttheelementwecopyinto

thetypeheldbythecontainerweareconstructing.

盡管不能宜接將?種容器內(nèi)的元素復(fù)制給另?種容器,但系統(tǒng)允許通過傳遞,對迭代器(第3.4甘)間接

實現(xiàn)該實現(xiàn)該功能。使用迭代器時,不要求容器類型相同。容器內(nèi)的元素類型也可以不相同,只要它們相互

兼容,能夠?qū)⒁獜?fù)制的元素轉(zhuǎn)換為所構(gòu)建的新容器的元素類型,即可實現(xiàn)復(fù)制。

Theiteratorsdenotearangeofelementsthatwewanttocopy.Theseelementsareusedtoinitialize

theelementsofthenewcontainer.Theiteratorsmarkthefirstandonepastthelastelementto

becopied.Wecanusethisformofinitializationtocopyacontainerthatwecouldnotcopydirectly.

Moreimportantly,wecanuseittocopyonlyasubsequenceoftheothercontainer:

迭代器標記了要復(fù)制的元素范圍,這些元素用于初始化新容器的元素。迭代器標記出要復(fù)制的第一個元素和

最后個元素。采用這種初始化形式可復(fù)制不能直接復(fù)制的容器。更重要的是,可以實現(xiàn)復(fù)制其他容器的一

個子序列:

//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:

回顧一下指針,我們知道指針就是迭代器,因此允許通過使用內(nèi)置數(shù)組中的一對指針初始化容器也就不奇怪

了:

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節(jié))計算數(shù)組的長度。將數(shù)組長度加到指向第一個元素的指針上就可以得到指向

超出數(shù)組末端的下一位置的指針。通過指向第一個元素的指針words和指向數(shù)組中最后?個元素的下?位

置的指針,實現(xiàn)了words2的初始化。其中第二個指針提供停止復(fù)制的條件,其所指向的位置上存放的元素

并沒有復(fù)制。

AllocatingandInitializingaSpecifiedNumberofElements

分配和初始化指定數(shù)目的元素

Whencreatingasequentialcontainer,wemayspecifyanexplicitsizeandan(optional)initializer

tousefortheelements.Thesizecanbeeitheraconstantornon-constantexpression.Theelement

initializermustbeavalidvaluethatcanbeusedtoinitializeanobjectoftheelementtype:

創(chuàng)建順序容器時,可顯式指定容器大小和?個(可選的)元素初始化式。容器大小可以是常量或非常量表達

式,元素初始化則必須是可用于初始化其元素類型的對象的值:

constlist<int>::size_typelistsize=64;

list<string>slist(list_size,〃eh?〃);//64strings,eachiseh?

Thiscodeinitializesslisttohave64elements,eachwiththevalueeh?.

這段代碼表示slist含有64個元素,每個元素都被初始化為“eh?”字符串。

Asanalternativetospecifyingthenumberofelementsandanelementinitializer,wecanalso

specifyonlythesize:

創(chuàng)建容器時,除了指定元素個數(shù),還可選擇是否提供元素初始化式。我們也可以只指定容器大?。?/p>

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.

不提供元素初始化式時,標準庫將為該容器實現(xiàn)值初始化(3.3.l&nbps;jn。采用這種類型的初始化,元

素類型必須是內(nèi)置或復(fù)合類型,或者是提供了默認構(gòu)造函數(shù)的類類型。如果元素類型沒有默認構(gòu)造函數(shù),則

必須顯式指定其元素初始化式。

Theconstructorsthattakeasizearevalidonlyforsequentialcontainers;they

arenotsupportedfortheassociativecontainers,

接受容器大小做形參的構(gòu)造函數(shù)只適用于順序容器,而關(guān)聯(lián)容器不支持這種初始化。

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.

創(chuàng)建和初始化一個vector對象有4種方式,為每種方式提供一個例子,并解

釋每個例子生成的vector對象包含什么值。

ExerciseExplainthedifferencesbetweentheconstructorthattakesacontainer

9.3:tocopyandtheconstructorthattakestwoiterators.

解釋夏制容器對象的構(gòu)造函數(shù)和使用兩個迭代器的構(gòu)造函數(shù)之間的差別。

9.1.2.ConstraintsonTypesthataContainerCanHold

9.1.2.容器內(nèi)元素的類型約束

Whilemosttypescanbeusedastheelementtypeofacontainer,therearetwoconstraintsthat

elementtypesmustmeet:

C++語言中,大多數(shù)類型都可用作容器的元素類型。容器元素類型必須滿足以下兩個約束:

?Theelementtypemustsupportassignment.

元素類型必須支持賦值運算。

?Wemustbeabletocopyobjectsoftheelementtype.

元素類型的對象必須可以復(fù)制。

Thereareadditionalconstraintsonthetypesusedasthekeyinanassociativecontainer,which

we'11coverinChapter10.

此外,關(guān)聯(lián)容器的鍵類型還需滿足其他的約束,我們將在第十章介紹相關(guān)內(nèi)容。

Mosttypesmeettheseminimalelementtyperequirements.Allofthebuilt-inorcompoundtypes,

withtheexceptionofreferences,canbeusedastheelementtype.Referencesdonotsupport

assignmentinitsordinarymeaning,sowecannothavecontainersofreferences.

大多數(shù)類型滿足上述最低限度的元素類型要求。除了引用類型外,所有內(nèi)置或復(fù)合類型都可用做元素類型。

引用不支持一般意義的賦值運算,因此沒有元素是引用類型的容器。

Withtheexceptionofthe10librarytypes(andtheautoptrtype,whichwecoverinSection17.1.9

(p.702)),allthelibrarytypesarevalidcontainerelementtypes.Inparticular,containers

themselvessatisfytheserequirements.Wecandefinecontainerswithelementsthatarethemselves

containers.OurSales_itemtypealsosatisifestheserequirements.

除輸入輸出(10)標準庫類型(以及第17.1.9節(jié)介紹的auto_ptr類型)之外,所有其他標準庫類型都是

有效的容器元素類型。特別地,容器本身也滿足上述要求,因應(yīng),可以定義元素本身就是容器類型的容器。

Sales_item類型也滿足上述要求。

The10librarytypesdonotsupportcopyorassignment.Therefore,wecannothaveacontainerthat

holdsobjectsofthe10types.

10庫類型不支持復(fù)制或賦值。因此,不能創(chuàng)建存放10類型對象的容器。

ContainerOperationsMayImposeAdditionalRequirements

容器操作的特殊要求

Therequirementtosupportcopyandassignmentistheminimalrequirementonelementtypes.In

addition,somecontaineroperationsimposeadditionalrequirementsontheelementtype.Ifthe

elementtypedoesn'tsupporttheadditionalrequirement,thenwecannotperformthatoperation:

Wecandefineacontainerofthattypebutmaynotusethatparticularoperation.

支持復(fù)制和賦值功能是容器元素類型的最低要求。此外,一些容器操作對元素類型還有特殊要求。如果元素

類型不支持這些特殊要求,則相關(guān)的容器操作就不能執(zhí)行:我們可以定義該類型的容器,但不能使用某些特

定的操作。

Oneexampleofanoperationthatimposesatypeconstraintistheconstructorsthattakeasingle

initializerthatspecifiesthesizeofthecontainer.Ifourcontainerholdsobjectsofaclass

type,thenwecanusethisconstructoronlyiftheelementtypehasadefaultconstructor.Most

typesdohaveadefaultconstructor,althoughtherearesomeclassesthatdonot.Asanexample,

assumethatFooisaclassthatdoesnotdefineadefaultconstructorbutthatdoeshaveaconstructor

thattakesanintargument.Now,considerthefollowingdeclarations:

其中?種需外加類型要求的容器操作是指定容器大小并提供單個初始化式的構(gòu)造函數(shù)。如果容器存儲類類型

的對象,那么只有當其元素類型提供默認構(gòu)造函數(shù)時,容器才能使用這種構(gòu)造函數(shù)。盡管有一些類沒有提供

默認構(gòu)造函數(shù),但大多數(shù)類類型都會有。例如,假設(shè)類Foo沒有默認構(gòu)造函數(shù),但提供了需要?個int型

形參的構(gòu)造函數(shù)。現(xiàn)在,考慮下面的聲明:

vector<Foo>empty;//ok:noneedforelementdefaultconstructor

vector<Foo>bad(10);//error:nodefaultconstructorforFoo

vector<Foo>ok(10,1);//ok:eachelementinitializedto1

WecandefineanemptycontainertoholdFooobjects,butwecandefineoneofagivensizeonly

ifwealsospecifyaninitializerforeachelement.

我們定義一個存放Foo類型對象的空容器,但是,只有在同時指定每個元素的初始化式時,才能使用給定

容器大小的構(gòu)造函數(shù)來創(chuàng)建同類型的容器對象。

Aswedescribethecontaineroperations,we'11notetheconstraints,ifany,thateachcontainer

operationplacesontheelementtype.

在描述容器操作時,我們應(yīng)該留意(如果有的話)每個操作對元素類型的約束。

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.必須用

空格隔開兩個相鄰的>符號,以示這是兩個分開的符號,否則,系統(tǒng)會認為?是單

個符號,為右移操作符,并導(dǎo)致編譯時錯誤。

ExercisesSection9.1.2

ExerciseDefinealistthatholdselementsthataredequesthatholdints.

9.4:

定義一個list對象來存儲deque對象里的元素,該deque對象存放int型

兀素。

ExerciseWhycanwenothavecontainersthatholdiostreatnobjects?

9.5:

為什么我們不可以使用容器來存儲iostream對象?

ExerciseGivenaclasstypenamedFoothatdoesnotdefineadefaultconstructor

9.6:butdoesdefineaconstructorthattakesintvalues,definealistofFoo

thatholds10elements.

假設(shè)有個名為Foo的類,這個類沒有定義默認構(gòu)造函數(shù),但提供了需要個

溫馨提示

  • 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

提交評論