Tải bản đầy đủ - 0 (trang)
Chapter 10. Containers, Iterators, and Algorithms

Chapter 10. Containers, Iterators, and Algorithms

Tải bản đầy đủ - 0trang

10.1Containers

Thefundamentalpurposeofacontaineristostoremultiple

objectsinasinglecontainerobject.Differentkindsof

containershavedifferentcharacteristics,suchasspeed,size,

andeaseofuse.Thechoiceofcontainerdependsonthe

characteristicsandbehavioryourequire.

InC++,thecontainersareimplementedasclasstemplates,so

youcanstoreanythinginacontainer.(Well,almostanything.

Thetypemusthavevaluesemantics,whichmeansitmust

behaveasanordinaryvalue,suchasanint.Valuescanbe

copiedandassignedfreely.Anoriginalanditscopymust

compareasequal.Somecontainersimposeadditional

restrictions.)



10.1.1StandardContainers

Thestandardcontainersfallintotwocategories:sequenceand

associativecontainers.Asequencecontainerpreservesthe

originalorderinwhichitemswereaddedtothecontainer.An

associativecontainerkeepsitemsinascendingorder(youcan

definetheorderrelation)tospeedupsearching.Thestandard

containersare:

deque

Adeque(double-endedqueue)isasequencecontainerthat

supportsfastinsertionsanddeletionsatthebeginningand

endofthecontainer.Insertingordeletingatanyother

positionisslow,butindexingtoanyitemisfast.Itemsare

notstoredcontiguously.Theheaderis.

list



Alistisasequencecontainerthatsupportsrapidinsertion

ordeletionatanypositionbutdoesnotsupportrandom

access.Itemsarenotstoredcontiguously.Theheaderis

.

map

multimap

Amap(ordictionary)isanassociativecontainerthatstores

pairsofkeysandassociatedvalues.Thekeysdeterminethe

orderofitemsinthecontainer.maprequiresuniquekeys.

multimappermitsduplicatekeys.Theheaderformapand

multimapis.

set

multiset

Asetisanassociativecontainerthatstoreskeysin

ascendingorder.setrequiresuniquekeys.multiset

permitsduplicatekeys.Theheaderforsetandmultisetis

.

vector

Avectorisasequencecontainerthatislikeanarray,except

thatitcangrowasneeded.Itemscanberapidlyaddedor

removedonlyattheend.Atotherpositions,insertingand

deletingitemsisslower.Itemsarestoredcontiguously.The

headeris.

Thesetandmapcontainersperforminsertions,deletions,and

searchesinlogarithmictime,whichimpliesatreeortree-like

implementation.Itemsmustbekeptinsortedorder,soahash

tableimplementationisnotallowed.Manyprogrammers

considerthelackofastandardhashtabletobeaserious

omission.WhentheC++standardisrevised,ahashtableis

likelytobeadded.TheSTLportprojectincludeshashtablebasedcontainers.SeeAppendixBforinformationabout



STLport.



10.1.2ContainerAdapters

Inadditiontothestandardcontainers,thestandardlibraryhas

severalcontaineradapters.Anadapterisaclasstemplatethat

usesacontainerforstorageandprovidesarestrictedinterface

whencomparedwiththestandardcontainers.Thestandard

adaptersare:

priority_queue

Apriorityqueueisorganizedsothatthelargestelementis

alwaysthefirst.Youcanpushanitemontothequeue,

examinethefirstelement,orremovethefirstelement.The

headeris.

queue

Aqueueisasequenceofelementsthatletsyouadd

elementsatoneendandremovethemattheotherend.

ThisorganizationiscommonlyknownasFIFO(first-in,firstout).Theheaderis.

stack

Astackisasequencethatletsyouaddandremove

elementsonlyatoneend.Thisorganizationiscommonly

knownasLIFO(last-in,first-out).Theheaderis.



10.1.3Pseudo-Containers

Thestandardlibraryhasafewclasstemplatesthataresimilar

tothestandardcontainersbutfailoneormoreofthe

requirementsforastandardcontainer:



bitset

Representsabitmaskofarbitrarysize.Thesizeisfixed

whenthebitsetisdeclared.Therearenobitsetiterators,

soyoucannotuseabitsetwiththestandardalgorithms.

SeeinChapter13fordetails.

basic_string

string

wstring

Representcharacterstrings.Thestringclasstemplates

meetalmostalloftherequirementsofasequence

container,andyoucanusetheiriteratorswiththestandard

algorithms.Nonetheless,theyfallshortofmeetingallthe

requirementsofacontainer,suchaslackingfrontand

backmemberfunctions.Theheaderis.

valarray

Representsanarrayofnumericvaluesoptimizedfor

computationalefficiency.Avalarraylacksiterators,andas

partoftheoptimization,thecompilerisfreetomake

assumptionsthatpreventvalarrayfrombeingusedwith

thestandardalgorithms.SeeinChapter13for

details.

vector

Aspecializationofthevectortemplate.Althoughvector<>

usuallymeetstherequirementsofastandardcontainer,the

vectorspecializationdoesnotbecauseyoucannot

obtainapointertoanelementofavectorobject.

SeeinChapter13fordetails.



10.1.4ContainerRequirements



Thissectionpresentstherulesthatgoverncontainers.Some

rulesapplytoallthestandardcontainers,andyoucanrelyon

thestandardbehaviorforallC++implementations.Otherrules

applyonlytosequencecontainers,andsomeapplyonlyto

associativecontainers.Ifyouwriteyourowncontainerclass

template,besuretofollowthesameconventionsandrulesthat

applytothestandardcontainers.



10.1.4.1Membertypes

const_iterator

Theiteratortypeforconstvalues.

const_reference

Aconstlvaluetypefortheitemsstoredinthecontainer.

Thisistypicallythesameastheallocator's

const_referencetype.

difference_type

Asignedintegraltypedenotingthedifferencebetweentwo

iterators.

iterator

Theiteratortype.

reference

Anlvaluetypefortheitemsstoredinthecontainer.Thisis

typicallythesameastheallocator'sreferencetype.

size_type

Anunsignedintegraltypethatcanholdanynonnegative



difference_typevalue.

value_type

Thetypeofitemstoredinthecontainer.Thisistypicallythe

sameasthefirsttemplateparameter.

Acontainerthatsupportsbidirectionaliteratorsshouldalso

definethereverse_iteratorandconst_reverse_iterator

types.

Anassociativecontainershoulddefinekey_typeasthekey

type,compare_typeasthekeycomparefunctionorfunctor,and

value_compareasafunctionorfunctorthatcomparestwo

value_typeobjects.

Optionally,acontainercandeclarepointerandconst_pointer

assynonymsoftheallocator'stypesofthesamename,and

allocator_typefortheallocator,whichistypicallythelast

templateparameter.



10.1.4.2Memberfunctions

Mostofthestandardmemberfunctionshaveacomplexitythat

isconstantorlinearinthenumberofelementsinthecontainer.

Someofthememberfunctionsforassociativemembersare

logarithmicinthenumberofelementsinthecontainer.Eachof

thedescriptionsinthissectionnotesthecomplexityofthe

function.

Acontainertemplateshouldhavethefollowingconstructors.

Youdonotneedtowriteseparateconstructorsinallcases;

sometimesyoucanusedefaultargumentsinsteadof

overloading.Ifanallocatorobjectissupplied,itiscopiedtothe

container;otherwise,adefaultallocatorisconstructed.Ineach

ofthefollowingdescriptions,containeristhenameofthe



containerclasstemplate.

container()

container(allocator_type)

Initializesthecontainertobeempty.Complexityis

constant.

container(constcontainer&that)

Initializesthecontainerwithacopyofalltheitemsandthe

allocatorfromthat.Complexityislinear.

Asequencecontainershouldhavethefollowingadditional

constructors:

container(size_typen,constvalue_type&x)

container(size_typen,constvalue_type&x,

allocator_type)

Initializesthecontainerwithncopiesofx.Complexityis

linearwithrespectton.

templatecontainer(InIterfirst,InIterlast)

template

container(InIterfirst,InIterlast,allocator_type)

Initializesthecontainerwithcopiesoftheitemsinthe

range[first,last).Complexityislinearwithrespectto

last-first.

IfInIterisanintegraltype,thecontainerisinitializedwith

firstcopiesoflast(convertedtovalue_type).

Complexityislinearwithrespecttofirst.

Anassociativecontainershouldhavethefollowingadditional

constructors:

container(key_comparecompare)



container(key_comparecompare,allocator_type)

Initializesanemptycontainerthatusescompareto

comparekeys.Complexityisconstant.

templatecontainer(InIterfirst,InIterlast,

key_comparecompare)

templatecontainer(InIterfirst,InIterlast,

key_comparecompare,allocator_type)

Initializesthecontainerwithcopiesoftheitemsinthe

range[first,last),comparingkeyswithcompare.

Complexityislinear.

Allcontainersmusthaveadestructor:

~container()

Callsthedestructorforeveryobjectinthecontainer,

perhapsbycallingclear.Complexityislinear.

Manymemberfunctionsarethesameforallthecontainer

templates,andwhenyouwriteyourowncontainertemplate,

youshouldimplementthesamememberfunctionswiththe

samebehaviors.Somearespecifictosequencecontainers,and

sometoassociativecontainers.Eachcontainertemplatecan

defineadditionalmembers.

iteratorbegin()

const_iteratorbegin()const

Returnsaniteratorthatpointstothefirstitemofthe

container.Complexityisconstant.

voidclear()

Erasesalltheitemsinthecontainer.Complexityislinear.

boolempty()



Returnstrueifthecontainerisempty(size()==0).

Complexityisconstant.

iteratorend()

const_iteratorend()const

Returnsaniteratorthatpointstoonepastthelastitemof

thecontainer.Complexityisconstant.(SeeSection10.2

laterinthischapterforadiscussionofwhat"onepastthe

lastitem"means.)

erase(iteratorp)

Erasestheitemthatppointsto.Forasequencecontainer,

erasereturnsaniteratorthatpointstotheitemthatcomes

immediatelyafterthedeleteditemorend().Complexity

dependsonthecontainer.

Foranassociativecontainer,erasedoesnotreturnavalue.

Complexityisconstant(amortizedovermanycalls).

erase(iteratorfirst,last)

Erasesalltheitemsintherange[first,last).Fora

sequencecontainer,erasereturnsaniteratorthatpointsto

theitemthatcomesimmediatelyafterthelastdeleteditem

orend().Complexitydependsonthecontainer.

Foranassociativecontainer,erasedoesnotreturnavalue.

Complexityislogarithmic,pluslast-first.

size_typemax_size()

Returnsthelargestnumberofitemsthecontainercan

possiblyhold.Althoughmanycontainersarenot

constrained,exceptbyavailablememoryandthelimitsof

size_type,othercontainertypes,suchasanarraytype,

mighthaveafixedmaximumsize.Complexityisusually



constant.

container&operator=(constcontainer&that)

Erasesallitemsinthiscontainerandcopiesalltheitems

fromthat.Complexityislinearinsize()+that.size().

size_typesize()

Returnsthenumberofitemsinthecontainer.Complexityis

usuallyconstant.

voidswap(constcontainer&that)

Swapstheelementsofthiscontainerwiththat.An

associativecontaineralsoswapsthecomparisonfunctionor

functions.Complexityisusuallyconstant.

Eachcontainershouldhaveallofitsequalityandrelational

operatorsdefined,eitherasmemberfunctionsor,preferably,as

functionsatthenamespacelevel.Namespace-levelfunctions

offermoreflexibilitythanmemberfunctions.Forexample,the

compilercanuseimplicittypeconversionsonthelefthand

operandbutonlyifthefunctionisnotamemberfunction.

Acontainerthatsupportsbidirectionaliteratorsshoulddefine

rbeginandrendmemberfunctionstoreturnreverseiterators.

Thefollowingfunctionsareoptional.Thestandardcontainers

provideonlythosefunctionsthathaveconstantcomplexity.

referenceat(size_typen)

const_referenceat(size_typen)const

Returnstheitematindexn,orthrowsout_of_rangeifn>=

size().

referenceback()

const_referenceback()const



Returnsthelastiteminthecontainer.Behaviorisundefined

ifthecontainerisempty.

referencefront()

const_referencefront()const

Returnsthefirstiteminthecontainer.Behaviorisundefined

ifthecontainerisempty.

referenceoperator[](size_typen)

const_referenceoperator[](size_typen)

Returnstheitematindexn.Behaviorisundefinedifn>=

size().

voidpop_back()

Erasesthelastiteminthecontainer.Behaviorisundefined

ifthecontainerisempty.

voidpop_front()

Erasesthefirstiteminthecontainer.Behaviorisundefined

ifthecontainerisempty.

voidpush_back(constvalue_type&x)

Insertsxasthenewlastiteminthecontainer.

voidpush_front(constvalue_type&x)

Insertsxasthenewfirstiteminthecontainer.

Asequencecontainershoulddefinethefollowingmember

functions.Thecomplexityofeachdependsonthecontainer

type.

iteratorinsert(iteratorp,constvalue_type&x)



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 10. Containers, Iterators, and Algorithms

Tải bản đầy đủ ngay(0 tr)

×