Tải bản đầy đủ - 0 (trang)
Chapter 82.  Use the accepted idioms to really shrink capacity and really erase elements

Chapter 82.  Use the accepted idioms to really shrink capacity and really erase elements

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

Summary

Useadietthatworks:Toreallyshedexcesscapacityfroma

container,usethe"swaptrick."Toreallyeraseelementsfroma

container,usetheerase-removeidiom.



Discussion

Somecontainers(e.g.,vector,string,deque)canendup

carryingaroundextracapacitythat'snolongerneeded.

AlthoughtheC++standardlibrarycontainersprovideno

guaranteedwaytotrimexcesscapacity,thefollowing"swap

trick"idiomworksinpracticetogetridofexcesscapacityfor

suchacoftypecontainer:



container(c).swap(c);//theshrink-to-fitidiomtoshed



Or,toemptycoutcompletely,clearingallcontainedelements

andsheddingallpossiblecapacity,theidiomis:



container().swap(c);//theidiomtoshedallcontentsa



Inrelatednews,acommonsurprisefornewSTLprogrammers

isthattheremovealgorithmdoesn'treallyremoveelements

fromacontainer.Ofcourse,itcan't;analgorithmjustworkson

aniteratorrange,andyoucan'tactuallyremovesomething

fromacontainerwithoutcallingacontainermemberfunction,

usuallyerase.Allremovedoesistoshufflevaluesaroundso

thattheelementsthatshouldn'tbe"removed"getshuffledup

towardthebeginningoftherange,andreturnaniteratortoone

pasttheendoftheunremovedelements.Toreallygetridof

them,thecalltoremoveneedstobefollowedbyacallto

erasehencethe"erase-remove"idiom.Forexample,toeraseall

elementsequaltovaluefromacontainerc,youcanwrite:

c.erase(remove(c.begin(),c.end(),value));



Prefertouseamemberversionofremoveorremove_ifona

containerthathasit.



Exceptions

Theusualshrink-to-fitidiomwon'tworkoncopy-on-write

implementationsofstd::string.Whatusuallydoesworkisto

calls.reserve(0)ortofakethestringoutbywriting

string(s.begin(),s.end()).swap(s);tousetheiterator

rangeconstructor.Inpractice,theseworktoshedexcess

capacity.(Betterstill,std::stringimplementationsare

abandoningcopy-on-write,whichisanoutdatedoptimization;

see[Sutter02].)



References

[Josuttis99]Đ6.2.1[Meyers01]Đ17,Đ32,Đ44[Sutter00]Đ7

[Sutter02]Đ7,Đ16



STL:Algorithms

Preferalgorithmstoloops.

BjarneStroustrup,[Stroustrup00]Đ18.12

Algorithmsareloopsonlybetter.Algorithmsarethe

"patterns"ofloops,addingfarmoresemanticcontentand

richnessthananakedforwoulddoalone.Ofcourse,the

momentyoustartusingalgorithmsyou'llalsostartusing

functionobjectsandpredicates;writethemcorrectly,and

usethemwell.

OurvoteforthemostvaluableIteminthissectiongoesto

Item83:UseacheckedSTLimplementation.



83.UseacheckedSTLimplementation

Summary

Discussion

Examples

References



Summary

Safetyfirst(seeItem6):UseacheckedSTLimplementation,

evenifit'sonlyavailableforoneofyourcompilerplatforms,

andevenifit'sonlyusedduringpre-releasetesting.



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

Chapter 82.  Use the accepted idioms to really shrink capacity and really erase elements

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

×