Tải bản đầy đủ - 0 (trang)
Appendix F. THE string TEMPLATE CLASS

Appendix F. THE string TEMPLATE CLASS

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

Thesespecializations,inturn,usethefollowingspecializations:

char_traits

allocator

char_traits

allocator

Youcancreateastringclassforsometypeotherthancharor

wchar_tbydefiningatraitsclassandusingthe

basic_stringtemplate.



ThirteenTypesandaConstant

Thebasic_stringtemplatedefinesseveraltypesthatareused

laterindefiningthemethods:

typedeftraitstraits_type;

typedeftypenametraits::char_typevalue_type;

typedefAllocatorallocator_type;

typedeftypenameAllocator::size_typesize_type;

typedeftypenameAllocator::difference_typedifference_type;

typedeftypenameAllocator::referencereference;

typedeftypenameAllocator::const_referenceconst_reference;

typedeftypenameAllocator::pointerpointer;

typedeftypenameAllocator::const_pointerconst_pointer;

Notethattraitsisatemplateparameterthatwillcorrespond

tosomespecifictype,suchaschar_traits;

traits_typewillbecomeatypedefforthatspecifictype.The

notation:

typedeftypenametraits::char_typevalue_type;

meansthatchar_typeisatypenamedefinedintheclass

representedbytraits.Thekeywordtypenameisusedtotell



thecompilerthattheexpressiontraits::char_typeisatype.

Forthestringspecialization,forexample,value_typewillbe

char.

Thesize_typeisusedlikesize_of,exceptthatitreturnsthe

sizeofastringintermsofthestoredtype.Forthestring

specialization,thatwouldbeintermsofchar,inwhichcase

size_typeisthesameassize_of.Itisanunsignedtype.

Thedifference_typeisusedtomeasurethedistancebetween

twoelementsofastring,againinunitscorrespondingtothe

sizeofasingleelement.Typically,itwouldbeasignedversion

ofthetypeunderlyingsize_type.

Forthecharspecialization,pointerwillbetypechar*,and

referencewillbetypechar&.However,ifyoucreatea

specializationforatypeofyourowndesign,thesetypes

(pointerandreference)couldrefertoclassesthathavethe

samepropertiesasthemorebasicpointersandreferences.

ToallowSTLalgorithmstobeusedwithstrings,thetemplate

definessomeiteratortypes:

typedef(modelsrandomaccessiterator)iterator;



typedef(modelsrandomaccessiterator)const_iterator;



typedefstd::reverse_iteratorreverse_iterato



typedefstd::reverse_iteratorconst_reverse_i

Thetemplatedefinesastaticconstant:

staticconstsize_typenpos=-1;



Becausesize_typeisunsigned,assigningavalueof-1actually

amountstoassigningthelargestpossibleunsignedvalueto

npos.Thisvaluecorrespondsto1greaterthanthelargest

possiblearrayindex.



DataInformation,Constructors,andSoOn

Constructorscanbedescribedintermsoftheeffectstheyhave.

Becausetheprivateportionsofaclasscanbeimplementationdependent,theseeffectsshouldbedescribedintermsof

informationavailableaspartofthepublicinterface.TableF.1

listsseveralmethodswhosereturnvaluescanbeusedto

describetheeffectsofconstructorsandofothermethods.Note

thatmuchoftheterminologyisfromtheSTL.



Method

begin()



TableF.1.SomestringDataMethods

Returns



Aniteratortothefirstcharacterinastring(alsoavailableina

constversion,whichreturnsaconstiterator).

end()

Aniteratorthatisthepast-the-endvalue(alsoavailableina

constversion).

rbegin()

Areverseiteratorthatisthepast-the-endvalue(alsoavailable

inaconstversion).

rend()

Areverseiteratorthatreferstothefirstcharacter(also

availableinaconstversion).

size()

Thenumberofelementsinastring,equaltothedistancefrom

begin()toend().

length()

Thesameassize().

capacity()

Theallocatednumberofelementsinastring.

max_size()

Themaximumallowablesizeofastring.

data()

ApointeroftypeconstcharT*tothefirstelementofanarray

whosefirstsize()elementsequalthecorrespondingelements

inthestringcontrolledby*this.Thepointershouldnotbe

assumedtobevalidafterthestringobjectitselfhasbeen

modified.

c_str()

ApointeroftypeconstcharT*tothefirstelementofanarray

whosefirstsize()elementsequalthecorrespondingelements

inthestringcontrolledby*thisandwhosenextelementisthe

charT(0)character(end-of-stringmarker)forthecharTtype.

Thepointershouldnotbeassumedtobevalidafterthestring

objectitselfhasbeenmodified.

get_allocator() Acopyoftheallocatorobjectusedtoallocatememoryforthe

stringobject.



Becarefulofthedifferencesamongbegin(),rend(),data(),

andc_str().Allrelatetothefirstcharacterinastring,butin

differentways.Thebegin()andrend()methodsreturn

iterators,whicharegeneralizationsofpointers,asdescribedin

theChapter16,"ThestringClassandtheStandardTemplate

Library,"discussionoftheSTL.Inparticular,begin()returnsa

modelofaforwarditerator,andrend()acopyofareverse

iterator.Bothrefertotheactualstringmanagedbythestring

object.(Becausethestringclassusesdynamicmemory

allocation,theactualstringcontentsneednotbeinsidethe

object,soweusethetermmanagetodescribetherelationship

betweenobjectandstring.)Youcanusethemethodsthat

returniteratorswiththeiterator-basedalgorithmsoftheSTL.

Forexample,youcanusetheSTLreverse()functionto

reversethecontentsofastring:

stringword;

cin>>word;

reverse(word.begin(),word.end());

Thedata()andc_str()methods,ontheotherhand,doreturn

ordinarypointers.Furthermore,thereturnedpointerspointto

thefirstelementofanarrayholdingthestringcharacters.This

arraycanbe,butneednotbe,acopyoftheoriginalstring

managedbythestringobject.(Theinternalrepresentation

usedbythestringobjectcanbeanarray,butitdoesn'thave

tobe.)Becauseitispossiblethatthereturnedpointersdopoint

totheoriginaldata,theyareconst,sotheycan'tbeusedto

alterthedata.Also,thepointersarenotguaranteedtobevalid

afterthestringismodified;thisreflectsthattheymaypointto

theoriginaldata.Thedifferencebetweendata()andc_str()

isthatthearrayc_str()pointstoisterminatedwithanull

character(orequivalent),whiledata()justguaranteesthe



actualstringcharactersarepresent.Thus,thec_str()method

canbeused,forexample,asanargumenttoafunction

expectingaC-stylestring:

stringfile("tofu.man");

ofstreamoutFile(file.c_str());

Similarly,data()andsize()couldbeusedwithafunctionthat

expectstoreceiveapointertoanarrayelementandavalue

representingthenumberofelementstoprocess:

stringvampire("Donotstakeme,ohmydarling!");

intvlad=byte_check(vampire.data(),vampire.size());

Animplementationcouldchoosetorepresentastringobject's

stringasadynamicallyallocatedC-stylestringandto

implementtheforwarditeratorasachar*pointer.Inthat

case,theimplementationcouldchoosetohavebegin(),

data(),andc_str()allreturnthesamepointer.Butitcould

justaslegitimately(ifnotaseasily)returnreferencestothree

differentdataobjects.

TableF.2liststhesixconstructorsandonedestructorforthe

basic_stringtemplateclass.Notethatallsixconstructors

haveanargumentofthefollowingform:

constAllocator&a=Allocator()

RecallthatthetermAllocatoristhetemplateparametername

foranallocatorclasstomanagememory.Theterm



Allocator()isthedefaultconstructorforthatclass.Thus,the

constructors,bydefault,usethedefaultversionofthe

allocatorobject,buttheygiveyoutheoptionofusingsome

otherversionoftheallocatorobject.Let'sexaminethe

constructorsindividually.

TableF.2.StringConstructors

ConstructorandDestructorPrototypes

explicitbasic_string(constAllocator&a=Allocator());

basic_string(constcharT*s,constAllocator&a=Allocator());

basic_string(constbasic_string&str,size_typepos=0,

size_typen=npos,constAllocator&a=Allocator());

basic_string(constcharT*s,size_typen,

constAllocator&a=Allocator());

basic_string(size_typen,charTc,constAllocator&a=Allocator());

template

basic_string(InputIteratorbegin,InputIteratorend,

constAllocator&a=Allocator());



~basic_string();



DefaultConstructor

Thisisthedefaultconstructor:

explicitbasic_string(constAllocator&a=Allocator());

Typically,youwouldacceptthedefaultargumentforthe



allocatorclassandwouldusetheconstructortocreateempty

strings:

stringbean;

wstringtheory;

Thefollowingrelationsholdaftertheconstructoriscalled:

Thedata()methodreturnsanon-nullpointertowhich0

canbeadded.

Thesize()methodreturns0.

Thereturnvalueforcapacity()isnotspecified.

Supposeyouassignthevaluereturnedbydata()toapointer

str.Thenthefirstconditionmeansstr+0isvalid,which,in

turn,meanstheexpressionstr[0]isvalid.



ConstructorUsinganArray

Thenextconstructorletsyouinitializeastringobjectfroma

C-stylestring;moregenerally,itletsyouinitializeacharT

specializationfromanarrayofcharTvalues:



basic_string(constcharT*s,constAllocator&a=Allocator());

Todeterminehowmanycharacterstocopy,theconstructor

appliesthetraits::length()methodtothearraypointedto

bys.(Thepointersshallnotbeanullpointer.)Forexample,



thestatement

stringtoast("Here'slookingatyou,kid.");

initializesthetoastobjectusingtheindicatedcharacterstring.

Thetraits::length()methodfortypecharwillusethenull

charactertodeterminehowmanycharacterstocopy.

Thefollowingrelationsholdaftertheconstructoriscalled:

Thedata()methodreturnsapointertothefirstelementof

acopyofthearrays.

Thesize()methodreturnsavalueequalto

traits::length().

Thecapacity()methodreturnsavalueatleastaslargeas

size().



ConstructorUsingPartofanArray

Thenextconstructorletsyouinitializeastringobjectfrom

partofaC-stylestring;moregenerally,itletsyouinitializea

charTspecializationfrompartofanarrayofcharTvalues:



basic_string(constcharT*s,size_typen,constAllocator&a=

Thisconstructorcopiesatotalofncharactersfromthearray

pointedtobystotheconstructedobject.Notethatitdoesn't

stopcopyingifshasfewercharactersthann.Ifnexceedsthe

lengthofs,theconstructorwillinterpretthecontentsof



memoryfollowingthestringasiftheyhelddataoftypecharT.

Theconstructorrequiresthatsisnotanullpointerandthatn


maximumpossiblenumberofelementsinastring.)Ifnequals

npos,theconstructorthrowsanout_of_rangeexception.

(Becausenisoftypesize_typeandnposisthemaximum

size_typevalue,ncannotbegreaterthannpos.)Otherwise,

thefollowingrelationsholdaftertheconstructoriscalled:

Thedata()methodreturnsapointertothefirstelementof

acopyofthearrays.

Thesize()methodreturnsn.

Thecapacity()methodreturnsavalueatleastaslargeas

size().



CopyConstructor

Thecopyconstructorprovidesseveralargumentswithdefault

values:



basic_string(constbasic_string&str,size_typepos=0,size_t

constAllocator&a=Allocator());

Callingitwithonlyabasic_stringargumentinitializesthenew

objecttothestringargument:

stringmel("I'mok!");



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

Appendix F. THE string TEMPLATE CLASS

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

×