Tải bản đầy đủ - 0 (trang)
Appendix G. THE STL METHODS AND FUNCTIONS

Appendix G. THE STL METHODS AND FUNCTIONS

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

MembersCommontoAllContainers

AllcontainersdefinethetypesinTableG.1.Inthistable,Xisa

containertype,suchasvector,andTisthetypestored

inthecontainer,suchasint.



Type



TableG.1.TypesDefinedforAllContainers

Value



X::value_type



T,theelementtype



X::reference



BehaveslikeT&

X::const_reference BehaveslikeconstT&

X::iterator

IteratortypepointingtoT,behaveslikeT*

X::const_iterator IteratortypepointingtoconstT,behaveslikeconstT*

X::difference_type Signedintegraltypeusedtorepresentthedistancefrom

oneiteratortoanother;forexample,thedifference

betweentwopointers

X::size_type

Unsignedintegraltypesize_typecanrepresentsizeofdata

objects,numberofelements,andsubscripts



Theclassdefinitionwilluseatypedeftodefinethese

members.Youcanusethesetypes,todeclaresuitable

variables.Forexample,thefollowingtakesaroundaboutwayto

replacethefirstoccurrenceof"bonus"inavectorofstring

objectswith"bogus"inordertoshowhowyoucanuse

membertypestodeclarevariables.

vectorinput;

stringtemp;

while(cin>>temp&&temp!="quit")

input.push_back(temp);

vector::iteratorwant=



find(input.begin(),input.end(),string("bonus"));

if(want!=input.end())

{

vector::referencer=*want;

r="bogus";

}

Thiscodemakesrareferencetotheelementininputtowhich

wantpoints.

Thesetypesalsocanbeusedinmoregeneralcodeinwhichthe

typeofcontainerandelementaregeneric.Forexample,

supposeyouwantamin()functionthattakesasitsargumenta

referencetoacontainerandreturnsthesmallestiteminthe

container.Thisassumesthatthe
valuetypeandthatyoudon'twanttousetheSTL

min_element()algorithm,whichusesaniteratorinterface.

Becausetheargumentcouldbevectororlist

ordeque,useatemplatewithatemplateparameter,

suchasBag,torepresentthecontainer.Sotheargumenttype

forthefunctionwillbeconstBag&b.Whataboutthereturn

type?Itshouldbethevaluetypeforthecontainer,thatis,

Bag::value_type.However,atthispoint,Bagisjustatemplate

parameter,andthecompilerhasnowayofknowingthatthe

value_typememberisactuallyatype.Butyoucanusethe

typenamekeywordtoclarifythataclassmemberisatypedef:



vector::value_typest;//vectoradefinedc



typenameBag::value_typem;//Baganasyetundefinedty

Forthefirstdefinition,thecompilerhasaccesstothevector

templatedefinition,whichstatesthatvalue_typeisatypedef.

Fortheseconddefinition,thetypenamekeywordpromisesthat

thecombinationBag::value_typeisatypedef.These

considerationsleadtothefollowingdefinition:

template

typenameBag::value_typemin(constBag&b)

{

typenameBag::const_iteratorit;

typenameBag::value_typem=*b.begin();

for(it=b.begin();it!=b.end();++it)

if(*it
m=*it;

returnm;

}

Youthencouldusethistemplatefunctionasfollows:

vectortemperatures;

//inputtemperaturevaluesintothevector



intcoldest=min(temperatures);

ThetemperaturesparameterwouldcauseBagtobeevaluated

asvectorandtypenameBag::value_typetobe

evaluatedasint.

Allcontainersalsocontainthememberfunctionsoroperations

listedinTableG.2.Again,Xisacontainertype,suchas

vector,andTisthetypestoredinthecontainer,suchas

int.Also,aandbarevaluesoftypeX.

TableG.2.MethodsDefinedforAllContainers

Method/Operation Description

begin()

end()

rbegin()

rend()

size()

maxsize()

empty()

swap()

==

!=

<

>operator>>

<=

>==operator>=>



Returnsaniteratortothefirstelement

Returnsaniteratortopast-the-end

Returnsareverseiteratortopast-the-end

Returnsareverseiteratortofirstelement

Returnsnumberofelements

Returnsthesizeofthelargestpossiblecontainer

Returnstrueifthecontainerisempty

Swapsthecontentsoftwocontainers

Returnstrueiftwocontainersarethesamesizeandhave

thesameelementsinthesameorder

a!=bisthesameas!(a==b)

Returnstrueifalexicographicallyprecedesb

a>bisthesameasb
a<=bisthesameas!(a>b)

a>=bisthesameas!(a


The>operatorforacontainerassumesthatthe>operatoris

definedforthevaluetype.Alexicographicalcomparisonisa

generalizationofalphabeticalsorting.Itcomparestwo

containerselementbyelementuntilencounteringanelementin

onecontainerthatdoesn'tequalthecorrespondingelementin

theothercontainer.Inthatcase,thecontainersareconsidered

tobeinthesameorderasthenon-correspondingpairof



elements.Forexample,iftwocontainersareidenticalthrough

thefirsttenelements,buttheeleventhelementinthefirst

containerislessthantheeleventhelementinthesecond

container,thefirstcontainerprecedesthesecond.Iftwo

containerscompareequaluntilonerunsoutofelements,the

shortercontainerprecedesthelonger.



AdditionalMembersforVectors,Lists,and

Deques

Vectors,lists,anddequesareallsequences,andtheyallhave

themethodslistedinTableG.3.Again,Xisacontainertype,

suchasvector,andTisthetypestoredinthecontainer,

suchasint,aisavalueoftypeX,tisavalueoftype

X::value_type,iandjareinputiterators,q2andpare

iterators,qandq1aredereferenceableiterators(youcanapply

the*operatortothem),andnisanintegerofX::size_type.

TableG.3.MethodsDefinedforVectors,Lists,andDeques

Method

Description

a.insert(p,t)



Insertsacopyoftbeforep;returnsaniteratorpointingtothe

insertedcopyoft.ThedefaultvaluefortisT(),thatis,the

valueusedfortypeTintheabsenceofexplicitinitialization.

a.insert(p,n,t) Insertsncopiesoftbeforep;noreturnvalue.

a.insert(p,i,j) Insertscopiesoftheelementsinrange[i,j)beforep,no

returnvalue.

a.resize(n,t) Ifn>a.size(),insertsn-a.size()copiesoftbeforea.end();

thasadefaultvalueofT(),thatis,thevalueusedfortypeTin

theabsenceofexplicitinitialization.Ifn
elementsfollowingthenthelementareerased.

a.assign(i,j) Replacesthecurrentcontentsofawithcopiesoftheelements

inrange[i,j).

a.assign(n,t) Replacesthecurrentcontentsofawithncopiesoft.The

defaultvaluefortisT(),thevalueusedfortypeTinthe

absenceofexplicitinitialization.

a.erase(q)

Erasestheelementpointedtobyq;returnsaniteratortothe

elementthathadfollowedq.

a.erase(q1,q2) Erasestheelementsintherange[q1,q2);returnsaniterator

pointingtotheelementq2originallypointedto.

a.clear()

Sameaserase(a.begin(),a.end()).

a.front()

Returns*a.begin()(thefirstelement).

a.back()

Returns*--a.end()(thelastelement).

a.push_back(t) Insertstbeforea.end().

a.pop_back()

Erasesthelastelement.



TableG.4listsmethodscommontotwooutofthethree

sequenceclasses.



Method



TableG.4.MethodsDefinedforSomeSequences

Description



Container



a.push_front(t) Insertsacopyoftbeforethefirstelement.



list,deque



a.pop_front()



Erasesthefirstelement.

Returns*(a.begin()+n).



list,deque



Returns*(a.begin()+n),throwsout_of_range

exceptionifn>a.size().



vector,

deque



a[n]

a.at(n)



vector,

deque



ThevectortemplateadditionallyhasthemethodsinTableG.5.

Here,aisavectorcontainerandnisanintegerof

X::size_type.



Method



TableG.5.AdditionalMethodsforVectors

Description



a.capacity() Returnsthetotalnumberofelementsthevectorcanholdwithout



requiringreallocation.

a.reserve(n) Alertsobjectathatmemoryforatleastnelementsisneeded.

Afterthemethodcall,thecapacitywillbeatleastnelements.

Reallocationoccursifnisgreaterthanthecurrentcapacity.Ifnis

greaterthana.max_size(),themethodthrowsalength_error

exception.



ThelisttemplateadditionallyhasthemethodsinTableG.6.

Here,aandbarelistcontainers,andTisthetypestoredin

thelist,suchasint,tisavalueoftypeT,iandjareinput

iterators,q2andpareiterators,qandq1aredereferenceable

iterators,andnisanintegerofX::size_type.Thetableuses

thestandardSTLnotationof[i,j)meaningtherangefromi

upto,butnotincludingj.



Method

a.splice(p,b)



TableG.6.AdditionalMethodsforLists

Description

Movesthecontentsoflistbtolista,insertingthem

beforep.



a.splice(p,b,i)



Movestheelementinlistbpointedtobyitobefore

positionpinlista.

a.splice(p,b,i,j)

Movestheelementsinrange[i,j)oflistbtobefore

positionpinlista.

a.remove(constT&t)

Erasesallelementsinlistahavingthevaluet.

a.remove_if(Predicate

Giventhatiisaniteratorintothelista,erasesall

pred)

valuesforwhichpred(*i)istrue.(APredicateisa

Booleanfunctionorfunctionobject,asdiscussedin

Chapter15,"Friends,Exceptions,andMore.")

a.unique()

Erasesallbutthefirstelementfromeachgroupof

consecutiveequalelements.

a.unique(BinaryPredicate Erasesallbutthefirstelementfromeachgroupof

bin_pred)

consecutiveelementsforwhichbin_pred(*i,*(i1))istrue.(ABinaryPredicateisaBooleanfunction

orfunctionobject,asdiscussedinChapter15.)

a.merge(b)

Mergesthecontentsoflistbwithlistausingthe<

operatordefinedforthevaluetype.Ifanelementina

isequivalenttoanelementinb,theelementfromais

placedfirst.Listbisemptyafterthemerge.

a.merge(b,Comparecomp) Mergesthecontentsoflistbwithlistausingthecomp

functionorfunctionobject.Ifanelementinais

equivalenttoanelementinb,theelementfromais

placedfirst.Listbisemptyafterthemerge.

a.sort()

Sortslistausingthe
a.sort(Comparecomp)

Sortslistausingthecompfunctionorfunctionobject.

a.reverse()

Reversestheorderoftheelementsinlista.



AdditionalMembersforSetsandMaps

Associativecontainers,ofwhichsetsandmapsaremodels,

haveaKeytemplateparameterandaComparetemplate

parameterindicating,respectively,thetypeofthekeyusedto

orderthecontentsandthefunctionobject,termeda

comparisonobject,usedtocomparekeyvalues.Fortheset

andmultisetcontainers,thestoredkeysarethestoredvalues,

sothekeytypeisthesameasthevaluetype.Forthemapand

multimapcontainers,thestoredvaluesofonetype(template

parameterT)areassociatedwithakeytype(template

parameterKey),andthevaluetypeispair.

Associativecontainersintroduceadditionalmemberstodescribe

thesefeatures,aslistedinTableG.7.



Type



TableG.7.TypesDefinedforAssociativeContainers

Value



X::key_type



Key,thekeytype



X::key_compare



Compare,whichhasadefaultvalueofless

X::value_compare Abinarypredicatetypethatisthesameaskey_compareforset

andmultisetandwhichsuppliesorderingforthepair
Key,T>valuesinamapormultimap.

X::mapped_type

T,thetypeoftheassociateddata(mapandmultimaponly)



AssociativecontainersprovidethemethodslistedinTableG.8.

Ingeneral,thecomparisonobjectneednotrequirethatvalues

withthesamekeyareidentical;thetermequivalentkeys

meansthattwovalues,whichmayormaynotbeequal,have

thesamekey.Inthetable,Xisacontainerclass,aisanobject

oftypeX.IfXusesuniquekeys(thatis,isasetormap),

a_uniqisanobjectoftypeX.IfXusesmultiplekeys(thatis,is

amultisetormultimap),a_eqisanobjectoftypeX.As

before,iandjareinputiteratorsreferringtoelementsof

value_type,[i,j)isavalidrange,pandq2areiteratorstoa,

qandq1aredereferenceableiteratorstoa,[q1,q2)isavalid



range,tisavalueofX::value_type(whichmaybeapair).

Also,kisavalueofX::key_type.

TableG.8.MethodsDefinedforSets,Multisets,Maps,andMultimaps

Method

Description

a.key_comp()



Returnsthecomparisonobjectusedinconstructinga.

a.value_comp()

Returnsanobjectofthevalue_comparetype.

a_uniq.insert(t) Insertsthevaluetintothecontaineraifandonlyifadoes

notyetcontainavaluewithanequivalentkey.Themethod

returnsavalueoftypepair.Thebool

componentistrueifinsertionoccurredandfalseotherwise.

Theiteratorcomponentpointstotheelementwhosekeyis

equivalenttothekeyoft.

a_eq.insert(t)

Insertstandreturnsaniteratorpointingtoitslocation.

a.insert(p,t)

Insertstusingpasahinttowhereinsert()shouldbeginits

search.Ifaisacontainerwithuniquekeys,insertiontakes

placeifandonlyifadoesn'tcontainanelementwithan

equivalentkey;otherwise,insertiontakesplace.Whetheror

notinsertiontakesplace,themethodreturnsaniterator

pointingtothelocationwithanequivalentkey.

a.insert(i,j)

Insertselementsfromtherange[i,j)intoa.

a.erase(k)

Erasesallelementsinawhosekeysareequivalenttokand

returnsthenumberofelementserased.

a.erase(q)

Erasestheelementpointedtobyq.

a.erase(q1,q2)

Erasestheelementsintherange[q1,q2).

a.clear()

Sameaserase(a.begin(),a.end()).

a.find(k)

Returnsaniteratorpointingtoanelementwhosekeyis

equivalenttok;returnsa.end()ifnosuchelementisfound.

a.count(k)

Returnsthenumberofelementshavingkeysequivalenttok.

a.lower_bound(k) Returnsaniteratortothefirstelementwithakeynotless

thank.

a.upper_bound(k) Returnsaniteratortothefirstelementwithakeygreater

thank.

a.equal_range(k) Returnsapairwhosefirstmemberisa.lower_bound(k)and

whosesecondmemberisa.upper_bound(k).

a.operator[](k) Returnsareferencetothevalueassociatedwiththekeyk

(mapcontainersonly).



STLFunctions

TheSTLalgorithmlibrary,supportedbythealgorithmand

numericheaderfiles,providesalargenumberofnon-member,

iterator-basedtemplatefunctions.AsdiscussedinChapter16,

thetemplateparameternamesarechosentoindicatewhat

conceptparticularparametersshouldmodel.Forexample,

ForwardIteratorisusedtoindicatethataparametershould,

attheminimum,modeltherequirementsofaforwarditerator,

andPredicateisusedtoindicateaparameterthatshouldbea

functionobjectwithoneargumentandaboolreturnvalue.The

standarddividesthealgorithmsintofourgroups:non-modifying

sequenceoperations,mutatingsequenceoperations,sorting

andrelatedoperators,andnumericoperations.Theterm

sequenceoperationindicatesthefunctiontakesapairof

iteratorsasargumentstodefinearange,orsequence,tobe

operatedupon.Thetermmutatingmeansthefunctionis

allowedtoalterthecontainer.



Non-ModifyingSequenceOperations

TableG.9summarizesthenon-modifyingsequenceoperations.

Argumentsarenotshown,andoverloadedfunctionsarelisted

justonce.Afullerdescriptionincludingtheprototypesfollows

thetable.Thus,youcanscanthetabletogetanideaofwhata

functiondoesandthenlookupthedetailsifyoufindthe

functionappealing.



Function

for_each()

find()

find_if()



TableG.9.Non-ModifyingSequenceOperations

Description

Appliesanon-modifyingfunctionobjecttoeachelementina

range.

Findsthefirstoccurrenceofavalueinarange.

Findsthefirstvaluesatisfyingapredicatetestcriterionina



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

Appendix G. THE STL METHODS AND FUNCTIONS

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

×